Java FileFilterUtils-class And Method Code Example


Here is an example of how to use the FileFilterUtils class from the org.apache.commons.io package in Java:

import java.io.File;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;

public class FileFilterUtilsExample {
    public static void main(String[] args) {
        // Create a filter that only accepts files with the .txt extension
        IOFileFilter txtFileFilter = FileFilterUtils.suffixFileFilter(".txt");
        // Create a filter that only accepts files that are larger than 100 bytes
        IOFileFilter minSizeFilter = FileFilterUtils.sizeFileFilter(100, true);
        // Combine the two filters
        IOFileFilter combinedFilter = FileFilterUtils.andFileFilter(txtFileFilter, minSizeFilter);

        // Use the combined filter to list all .txt files larger than 100 bytes in the current directory
        File dir = new File(".");
        File[] files = dir.listFiles(combinedFilter);
        for (File file : files) {
            System.out.println(file.getName());
        }
    }
}

In this example, we use the FileFilterUtils class to create two filters:

  • txtFileFilter: a filter that only accepts files with the ".txt" extension, using FileFilterUtils.suffixFileFilter(".txt")
  • minSizeFilter: a filter that only accepts files that are larger than 100 bytes, using FileFilterUtils.sizeFileFilter(100, true)

Then we combine these two filters using the FileFilterUtils.andFileFilter(IOFileFilter,IOFileFilter) method.

Finally, we use the combined filter to list all ".txt" files larger than 100 bytes in the current directory by calling the listFiles() method on a File object representing the current directory, and passing in the combinedFilter object as an argument.

You can also use FileFilterUtils.orFileFilter(IOFileFilter,IOFileFilter) to combine filters and return a filter that accepts files accepted by either of the two filters.

import java.io.File;
import org.apache.commons.io.filefilter.FileFilterUtils;

public class FileFilterUtilsExample {
    public static void main(String[] args) {
        // Create a filter that only accepts files with the .txt or .log extension
        IOFileFilter txtFileFilter = FileFilterUtils.suffixFileFilter(".txt");
        IOFileFilter logFileFilter = FileFilterUtils.suffixFileFilter(".log");
        IOFileFilter combinedFilter = FileFilterUtils.orFileFilter(txtFileFilter, logFileFilter);

        // Use the combined filter to list all .txt or .log files in the current directory
        File dir = new File(".");
        File[] files = dir.listFiles(combinedFilter);
        for (File file : files) {
            System.out.println(file.getName());
        }
    }
}

In this example, the FileFilterUtils.orFileFilter(IOFileFilter,IOFileFilter) will return