A Java FileFilter example (list files in a directory with a filter)

Java FileFilter FAQ: How do I implement a file filter in Java so I can limit the possible files that are shown to a user in a "select file" dialog, or limit the list of files that I see when listing the files in a directory?

At the moment I don't have an example of how to use a Java FileFilter with a JDialog based FileChooser, but I hope the following Java FileFilter example will help (a) demonstrate how to limit the list of files that is created when you look at a directory in Java, and (b) demonstrate the hard part of creating a Java FileFilter for use with a Java FileChooser.

A Java FileFilter implementation

First, here’s a Java class named ImageFileFilter that implements the Java FileFilter interface. I’ve written this class so it will match filenames that end with image file extensions, i.e., extensions like jpg, png, and gif. The key thing about implementing a FileFilter is that you need to implement a method named accept, as shown below:

import java.io.*;

/**
 * A class that implements the Java FileFilter interface.
 */
public class ImageFileFilter implements FileFilter
{
  private final String[] okFileExtensions = new String[] {"jpg", "png", "gif"};

  public boolean accept(File file)
  {
    for (String extension : okFileExtensions)
    {
      if (file.getName().toLowerCase().endsWith(extension))
      {
        return true;
      }
    }
    return false;
  }
}

Using my Java FileFilter class

Now that my ImageFileFilter implements the FileFilter interface, we can use it in a simple test class.

As shown in the source code below, I get a list of image files from a directory by passing a reference to my ImageFileFilter class into the listFiles method of the java.io.File class:

import java.io.*;
import java.util.*;

public class FileFilterTest
{
  public static void main(String[] args)
  {
    new FileFilterTest();
  }

  public FileFilterTest()
  {
    File dir = new File("/Users/al");

    // list the files using our FileFilter
    File[] files = dir.listFiles(new ImageFileFilter());
    for (File f : files)
    {
      System.out.println("file: " + f.getName());
    }
  }
}

Hopefully the rest of this source code example is easy to follow. Just change the directory to whatever directory you want to get a listing of.

As a final note, in production code you should test that the "directory" you're looking at is really a directory. To do that you'd use code like this:

if (dir.isDirectory())
{
  // do something here ...
}

Summary

I hope this Java FileFilter example has been helpful. As usual, if you have any questions or comments, just leave a note in the Comments section below, and I'll try to help.