A Java FileFilter example for image files

If you need some source code for a Java FileFilter for image files, this code can get you started:

import java.io.FileFilter;

class ImageFileFilter implements FileFilter {
    private final String[] okFileExtensions = new String[] { "jpg", "jpeg", "png", "gif" };

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

The important part of that code is that my ImageFileFilter extends FileFilter, and then I implement an accept method as shown, which returns true if I think the file is an image file, and false otherwise.

You can use that file filter with the Java File class like this:

File dir = new File(canonDirectoryName);
File[] filesInDir = dir.listFiles(new ImageFileFilter());
if (filesInDir.length == 0) return;
// your custom code here ...

As mentioned, if you need some code for a Java FileFilter class that works with image files, I hope this is helpful.