Listing files in a directory matching a pattern in Java

Omar Kooheji picture Omar Kooheji · Jan 20, 2010 · Viewed 112.9k times · Source

I'm looking for a way to get a list of files that match a pattern (pref regex) in a given directory.

I've found a tutorial online that uses apache's commons-io package with the following code:

Collection getAllFilesThatMatchFilenameExtension(String directoryName, String extension)
{
  File directory = new File(directoryName);
  return FileUtils.listFiles(directory, new WildcardFileFilter(extension), null);
}

But that just returns a base collection (According to the docs it's a collection of java.io.File). Is there a way to do this that returns a type safe generic collection?

Answer

Kevin picture Kevin · Jan 20, 2010

See File#listFiles(FilenameFilter).

File dir = new File(".");
File [] files = dir.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(".xml");
    }
});

for (File xmlfile : files) {
    System.out.println(xmlfile);
}