How to Use a FileFilter in Java to List Files

In this example we use a FileFilter to list files of a certain type. To implement the FileFilter interface we need to create an accept() method which takes a object as parameter.
In the method we check whether the name ends with “.txt” and if so we return true, else false.
When we have created the FileFilter we can pass it to the listFiles method of the class which will use it to return an array of all files that the filter returned true for in its accept method.
In the example we check the C:\temp folder for files ending with the .txt extension.

First of all we check if the directory specified exists and if it is in fact a directory (and not a file).

The output from the code will be a list with every file in the C:\temp directory with the .txt extension.

Search for more Java info on this site here:
Custom Search

Please type any questions here.