Java WildcardFilter-class And Method Code Example

Here is an example of how to use the WildcardFilter class from the Apache Commons IO library to filter files based on a wildcard pattern:



public class Main {
    public static void main(String[] args) {
        // Wildcard pattern to filter
        String wildcardPattern = "*.txt";

        // Creating a FileFilter
        FileFilter wildcardFilter = new WildcardFilter(wildcardPattern);
        File dir = new File("/path/to/directory");

        // Retrieving files that match the filter
        File[] files = dir.listFiles((FileFilter) wildcardFilter);

        for (File file : files) {

In this example, the WildcardFilter is used to filter files in a directory based on a wildcard pattern. The filter is created with the wildcard pattern of "*.txt". The listFiles method is then used to retrieve all files in the directory that match the filter. The names of the filtered files are then printed to the console.

It's worth mentioning that WildcardFilter is similar to WildcardFileFilter, the difference is that WildcardFilter implements IOFileFilter interface instead of FileFilter and it can be used with the FileUtils.listFiles() method.

Also you can pass multiple patterns using an array of wildcard patterns.

String[] wildcardPatterns = {"*.txt", "*.log"};
FileFilter wildcardFilter = new WildcardFilter(wildcardPatterns);

It will filter files with txt and log extensions.