Find Files in Directory Using Java

It’s surprisingly (or not, depending on your opinion of Java) difficult to get a list of files matching a pattern in a directory. For example, C# makes this really easy. :) In Java, you need to create a class that implements the java.io.FileFilter interface.

Below is a simple example of how this interface could implemented:

import java.io.*;
 
public class SimpleFileFilter implements FileFilter
{
    private String _pattern;
 
    public SimpleFileFilter(String pattern)
    {
	_pattern = pattern;
    }
 
    public boolean accept(File file)
    {
	return file.getName().contains(_pattern);
    }
}

You would then search for a list of files matching a specific pattern in the following way, which would give you all the files with a .xml extension:

File dir = new File("C:\\Temp");
File[] files = dir.listFiles(new SimpleFileFilter(".xml"));

Note that this simple filter does not work for wild cards (for example, *xml*), however you can implement whatever logic you want in your FileFilter class, so that would be feasible with some custom code. Here is another post that shows how to do this.

2 Responses to “Find Files in Directory Using Java”

  1. Thank you very much for this post. I took the WildCardFileFilter class and worked perfectly for me!

    I needed a way to grab files which will be appended with the current date but only needed to search on the file names and not worry about the dates so throwing FILENAME_* grabbed all respective files first try!

    Thank you very much!

  2. Thanks a lot for your code. It worked like charm.

Leave a Reply