Java SuffixFileFilter-class And Method Code Example
Here is an example of how to use the SuffixFileFilter class from the Apache Commons IO library to filter files based on their file extension:
import org.apache.commons.io.filefilter.SuffixFileFilter;
import java.io.File;
import java.io.FileFilter;
public class Main {
public static void main(String[] args) {
// File extension to filter
String extension = "txt";
// Creating a FileFilter
FileFilter extensionFilter = new SuffixFileFilter(extension);
File dir = new File("/path/to/directory");
// Retrieving files that match the filter
File[] files = dir.listFiles(extensionFilter);
for (File file : files) {
System.out.println(file.getName());
}
}
}
In this example, the SuffixFileFilter
is used to filter files in a directory based on their file extension. The filter is created with the file extension 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 if you want to filter multiple extensions, you can pass an array of extension to the SuffixFileFilter constructor, like this:
FileFilter extensionFilter = new SuffixFileFilter(new String[] { "txt", "log" });
It will filter files with txt and log extensions.