Java NameFileFilter-class And Method Code Example


Here's an example of how to use the NameFileFilter class from the Apache Commons IO library to filter files based on their names:

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

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");
        File[] matchingFiles = dir.listFiles((FileFilter) new NameFileFilter(names));

        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 NameFileFilter as an argument. The NameFileFilter constructor takes a string array as an argument, which is the names to search for. The filtered matching files are stored in the matchingFiles array, and their names are printed out using a for loop.

You can also pass a single string to the constructor, in this case the class will filter the files that match the string passed as parameter.

File dir = new File("/path/to/directory");
File[] matchingFiles = dir.listFiles((FileFilter) new NameFileFilter("file1.txt"));

You can also use wildcard as filter criteria, for example:

File dir = new File("/path/to/directory");
File[] matchingFiles = dir.listFiles((FileFilter) new NameFileFilter("*.txt"));

This will return all files with extension .txt.