Java FileNameFilter Example

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

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.

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.

That’s all for java FileNameFilter example. I hope it will help you in listing files in a directory using some criteria.

By admin

Leave a Reply