Java: How to list all files in a directory that match a filename extension

I just ran across this Java method I used to create a list of all files in a directory that match a specific filename pattern, or more specifically, matched the same filename extension.

The Java “list files in a directory” source code

First, here’s the source code for this Java “list files” method. I’ll follow this code with a brief description:

Collection getListOfAllConfigFiles(String directoryName)
{
    File directory = new File(directoryName);
    return FileUtils.listFiles(directory, new WildcardFileFilter("*.cfg"), null);
}

As you can see, this method takes the name of a directory as input, and then uses the FileUtils.listFiles method, and the WildcardFileFilter class to create a list of all files in the directory that have the same filename extension, in this case, they all end with the extension .cfg.

The Apache Commons IO project

The only magic here is that the FileUtils and WildcardFileFilter classes come from the Apache Commons IO project. When using this method, I have these import statements at the top of my Java class:

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;

I’ve found that downloading the Commons IO jar file and using their classes and methods make working with a filesystem, files, and directories, much easier when programming with Java. They have a lot of convenience methods that just make Java filesystem programming easier, including this filename extension / pattern / wildcard example.

Slightly improved Java “list files” method

We can easily improve that method by making it a little more general, and letting the calling program pass in the desired file extension, like this:

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

Either way, this is the easiest way I know to use Java to get a list of all files in a directory that match a certain filename pattern, or in this case, all the files that match a filename extension.