Finding Files with Wildcard Patterns in Java
Identifying files matching a specific wildcard pattern can be daunting in Java. To tackle this challenge, consider the following approaches:
Using org.apache.commons.io.filefilter.WildcardFileFilter
Create a FileFilter instance using WildcardFileFilter:
FileFilter fileFilter = new WildcardFileFilter("sample*.txt");
Apply the filter to a directory to list matching files:
File dir = new File("."); File[] files = dir.listFiles(fileFilter);
Handling Relative Paths
To account for relative paths in directories:
Iterate Through Subdirectories:
FileFilter dirFilter = new WildcardFileFilter("Test*"); File[] subdirs = new File(".").listFiles(dirFilter); for (File subdir : subdirs) { if (subdir.isDirectory()) { File[] files = subdir.listFiles(fileFilter); } }
Use Recursion:
File current = ...; // start at any directory File[] files = new ArrayList<>(); processFiles(files, current, fileFilter); private void processFiles(List<File> files, File dir, FileFilter filter) { File[] subdirs = dir.listFiles(dirFilter); for (File subdir : subdirs) { if (subdir.isDirectory()) { processFiles(files, subdir, filter); } else if (filter.accept(subdir)) { files.add(subdir); } } }
Alternative Approaches
The above is the detailed content of How Can I Efficiently Find Files Matching Wildcard Patterns in Java?. For more information, please follow other related articles on the PHP Chinese website!