Filtering multiple lines / extensions with FileNameFilter

How can I filter more than one extension, FileNameFilter only allows one line at a time.

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));
    }

      

+3


source to share


1 answer


Rewrite your filter as shown below.

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;
    }
}

      



Then you can initialize it with a few extensions: new GenericExtFilter("mp4", "flv", "wmv");

.

The method accept

will iterate over the array, and if it finds a suitable extension, it will return true, if not, false.

+3


source







All Articles