使用FileNameFilter过滤多个字符串/扩展名

时间:2014-09-18 01:45:51

标签: java

如何过滤多个扩展名,FileNameFilter一次只允许一个字符串..

FileNameFilter API

//  filter extension, but only allow filtering single extension.
//  i want to filter three extension like mp4, flv, wmv 

public class GenericExtFilter implements FilenameFilter {

    private String ext;

    public GenericExtFilter(String ext) {
        this.ext = ext;
    }

    public boolean accept(File dir, String name) {
        return (name.endsWith(ext));
    }

1 个答案:

答案 0 :(得分:3)

重写您的过滤器,如下所示。

public class GenericExtFilter implements FilenameFilter {
    private String[] exts;

    public GenericExtFilter(String... exts) {
        this.exts = exts;
    }

    @Override
    public boolean accept(File dir, String name) {
        for (String ext : exts) {
             if (name.endsWith(ext)) {
                 return true;
             }
        }

        return false;
    }
}

然后,您可以使用多个扩展程序对其进行初始化:new GenericExtFilter("mp4", "flv", "wmv");

accept方法将遍历数组,如果找到匹配的扩展名,则返回true,否则返回false。