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