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 java.io.File 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 java.io.File 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


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">