Exclude File Filter

Mark Estrada :

I used the following code to filter files that are having the following extension

FileFilter fileFilter= new WildcardFileFilter("*.docx");
File[] sampleFiles= filesDirectory.listFiles(fileFilter);

But what if I want the opposite, I want to exclude files that are having this extension. Currently I have the following code

public class FileFilter {
    public static void main(String[] args) {
        File dir = new File("C:\\temp\\filter-exclude");

        File[] files = dir.listFiles(new ExcludeFilter());
        for (File f : files) {
            System.out.println("file: " + f.getName());
        }
    }

    public static class ExcludeFilter implements java.io.FileFilter {

        @Override
        public boolean accept(File file) {
            if (file.getName().toLowerCase().endsWith("docx")) {
                return false;
            }
            return true;
        }

    }
}

But not sure if there are classes already for this. Is there such a class?

Thilo :

You could compose with the notFileFilter:

dir.listFiles(
 FileFilterUtils.notFileFilter(
   FileFilterUtils.suffixFileFilter(".docx")))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112574&siteId=1