Search for Files Recursively in Java
In this post, I explained how to find files using wildcard patterns. This current post builds on the code from that post and allows you to do a wildcard search recursively (in all subdirectories) rather than just in a single directory. Notice that this method calls itself (which is what recursiveness is all about).
import java.util.*; import java.io.*; public static ArrayList<File> GetFilesInDirRecursively(String dirPath, String pattern) throws Exception { File directory = new File(dirPath); FilenameFilter filter = new WildCardFilenameFilter(pattern); ArrayList<File> results = new ArrayList<File>(); for (File file : directory.listFiles()) { if (filter.accept(directory, file.getName())) results.add(file); else { if (file.isDirectory()) results.addAll(GetFilesInDirRecursively(file.getAbsolutePath(), pattern)); } } return results; }