Java NotFileFilter-class And Method Code Example


Here's an example of how to use the NotFileFilter class from the Apache Commons IO library to filter files based on the negation of a provided filter:

import java.io.File;
import org.apache.commons.io.filefilter.NameFileFilter;
import org.apache.commons.io.filefilter.NotFileFilter;

public class Main {
    public static void main(String[] args) {
        // The name pattern to search for
        String[] names = new String[]{"file1.txt", "file2.txt"};

        File dir = new File("/path/to/directory");

        //Create the filter that will match names
        FileFilter nameFilter = new NameFileFilter(names);
        //Create the filter that negates the name filter
        FileFilter notNameFilter = new NotFileFilter(nameFilter);

        File[] nonMatchingFiles = dir.listFiles(notNameFilter);

        for (File file : nonMatchingFiles) {
            System.out.println(file.getName());
        }
    }
}

In this example, /path/to/directory should be replaced with the path to the directory you want to search through. The listFiles method is called on the dir object, and it takes an instance of NotFileFilter as an argument. The NotFileFilter constructor takes a FileFilter as an argument, and it negates the filter provided. In this case, we are negating a NameFileFilter that filters files by name. The filtered non-matching files are stored in the nonMatchingFiles array, and their names are printed out using a for loop.

You can use any other filter to negate the results. The NotFileFilter is useful when you want to exclude a certain type of file from the list, for example if you want to list all files except the hidden files, you can use the HiddenFileFilter as parameter for the NotFileFilter constructor.

import org.apache.commons.io.filefilter.HiddenFileFilter;
FileFilter notHiddenFilter = new NotFileFilter(HiddenFileFilter.HIDDEN);
File[] nonHiddenFiles = dir.listFiles(notHiddenFilter);