Java File listFiles(FileFilter filter) method example

HQ ┬╗ Java Tutorial ┬╗ ┬╗ File ┬╗ listFiles(FileFilter filter) method example
Java File listFiles(FileFilter filter) method example 2018-02-16T07:26:40+00:00 listFiles(FileFilter filter)


On this document we will be showing a java example on how to use the listFiles(FileFilter filter) method of File Class. This method returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. The behavior of this method is the same as that of the listFiles() method, except that the pathnames in the returned array must satisfy the filter. If the given filter is null then all pathnames are accepted. Otherwise, a pathname satisfies the filter if and only if the value true results when the FileFilter.accept(File) method of the filter is invoked on the pathname.


SecurityException – If a security manager exists and its SecurityManager.checkRead(String) method denies read access to the directory

Method Syntax

public File[] listFiles(FileFilter filter)

Method Argument

Data Type Parameter Description
FileFilter filter A file filter

Method Returns

This method returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.


Requires Java 1.2 and up

Java File listFiles(FileFilter filter) Example

Below is a java code┬ádemonstrates the use of listFiles(FileFilter filter)┬ámethod of File class. The example presented might be simple however it shows the behaviour of the listFiles(FileFilter filter) method of File class. Because thelistFiles(FileFilter filter) method returns an array of Files┬áthat denotes the filenames inside the directory if and only if the abstract pathname denotes directory, thus we have first put a check if the file is a directory or not. It wouldn’t make sense to just blindly list down the filenames without making sure that the pathname is a directory because the returned value would be null. Make sure to have it checked out to avoid unnecessary issues in using this method.We have use the filter isFile() which generally list only files excluding directories.

Sample Output

Below is the sample output when you run the above example.

java lang File listFiles(FileFilter filter) example output

Contact Info


Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.