Java FilenameFilter interface can be implemented to filter file names when File
class listFiles()
method is used.
Java FilenameFilter
Java FileNameFilter interface has method boolean accept(File dir, String name)
that should be implemented and every file is tested for this method to be included in the file list.
From Java 8 onwards, FileNameFilter is a functional interface since it has a single method.
Java FilenameFilter Example
We can use FilenameFilter in java to find all the files of a specific extension in a directory. Below is the program showing how to use FileNameFilter in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.journaldev.files; import java.io.File; import java.io.FilenameFilter; public class FileNameFilterExample { public static void main(String[] args) { String dir = "/Users/pankaj/temp"; String extension = ".doc"; findFiles(dir, extension); } private static void findFiles(String dir, String extension) { File file = new File(dir); if (!file.exists()) System.out.println(dir + " Directory doesn't exists"); File[] listFiles = file.listFiles(new MyFileNameFilter(extension)); // File[] listFiles = file.listFiles((d, s) -> { // return s.toLowerCase().endsWith(extension); // }); if (listFiles.length == 0) { System.out.println(dir + "doesn't have any file with extension " + extension); } else { for (File f: listFiles) System.out.println("File: " + dir + File.separator + f.getName()); } } // FileNameFilter implementation public static class MyFileNameFilter implements FilenameFilter { private String extension; public MyFileNameFilter(String extension) { this.extension = extension.toLowerCase(); } @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(extension); } } } |
MyFileNameFilter
class implements FilenameFilter
interface and accept method checks if the file name ends with specific extension or not. In the main method, we are invoking findFiles
method that is using MyFileNameFilter to list xml files only. Note that MyFileNameFilter is written in a way to ignore case while checking for file extension.
FileNameFilter in java with lambda expression
Since FileNameFilter is a functional interface, we can reduce the above code by using a lambda expression. We won’t need to write the implementation at all.
Below is the code to use the FileNameFilter with a lambda expression.
1 2 3 4 5 |
File[] listFiles = file.listFiles((d, s) -> { return s.toLowerCase().endsWith(extension); }); |
That’s all for java FileNameFilter example. I hope it will help you in listing files in a directory using some criteria.