Java OrFileFilter-class And Method Code Example


Here's an example of how to use the OrFileFilter class from the Apache Commons IO library to filter files based on the logical "or" of two or more provided filters:

import java.io.File;
import org.apache.commons.io.filefilter.NameFileFilter;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.OrFileFilter;

public class Main {
    public static void main(String[] args) {
        File dir = new File("/path/to/directory");

        //Create the filter that will match names
        FileFilter nameFilter = new NameFileFilter("file1.txt");
        //Create the filter that will match hidden files
        FileFilter hiddenFilter = HiddenFileFilter.HIDDEN;
        //Create the filter that will match the 'or' of both filters
        FileFilter orFilter = new OrFileFilter(nameFilter, hiddenFilter);

        File[] matchingFiles = dir.listFiles(orFilter);

        for (File file : matchingFiles) {
            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 OrFileFilter as an argument. The OrFileFilter constructor takes two or more FileFilter instances as arguments, and it returns all files that match at least one of the provided filters. In this case, we are using a NameFileFilter that filters files by name and a HiddenFileFilter that filters hidden files. The filtered matching files are stored in the matchingFiles array, and their names are printed out using a for loop.

You can use any number of filters to match multiple conditions. For example, if you want to list files that are either hidden or that have a certain extension, you can use the HiddenFileFilter and the SuffixFileFilter as the parameters for the OrFileFilter constructor.

import org.apache.commons.io.filefilter.SuffixFileFilter;
FileFilter suffixFilter = new SuffixFileFilter(".txt");
FileFilter orFilter = new OrFileFilter(HiddenFileFilter.HIDDEN, suffixFilter);
File[] matchingFiles = dir.listFiles(orFilter);

This will return all files that are either hidden or have the .txt extension.