Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude File Filter

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?

like image 712
Mark Estrada Avatar asked Feb 24 '26 08:02

Mark Estrada


1 Answers

You could compose with the notFileFilter:

dir.listFiles(
 FileFilterUtils.notFileFilter(
   FileFilterUtils.suffixFileFilter(".docx")))
like image 65
Thilo Avatar answered Feb 25 '26 20:02

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!