How to make FileFilter in java?

Since Java7 you can simply use FileNameExtensionFilter(String description, String... extensions)

A simple JFileChooser analog to the example would be:

JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt"));

I know the question was answered long ago, but this is actually the simplest solution.


From JDK8 on words it is as simple as

final String extension = ".java";
final File currentDir = new File(YOUR_DIRECTORY_PATH);
File[] files = currentDir.listFiles((File pathname) -> pathname.getName().endsWith(extension));

Here you will find some working examples. This is also a good example of FileFilter used in JFileChooser.

The basics are, you need to override FileFilter class and write your custom code in its accpet method. The accept method in above example is doing filtration based on file types:

public boolean accept(File file) {
    if (file.isDirectory()) {
      return true;
    } else {
      String path = file.getAbsolutePath().toLowerCase();
      for (int i = 0, n = extensions.length; i < n; i++) {
        String extension = extensions[i];
        if ((path.endsWith(extension) && (path.charAt(path.length() 
                  - extension.length() - 1)) == '.')) {
          return true;
        }
      }
    }
    return false;
}

Or more simpler to use is FileNameFilter which has accept method with filename as argument, so you don't need to get it manually.


Try something like this...

String yourPath = "insert here your path..";
File directory = new File(yourPath);
String[] myFiles = directory.list(new FilenameFilter() {
    public boolean accept(File directory, String fileName) {
        return fileName.endsWith(".txt");
    }
});