Java FileFilter
is a filter for File objects denoting the files and subdirectories in a given directory. It is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
The use of FileFilter is similar to FilenameFilter except the latter uses only the name of the file to make the decision. The FileFilter accepts File
objects and thus can be used to filter the files based on other attributes such as read-only.
1. FileFilter class
The FileFilter
class has only a single method accept()
that tests whether or not the specified abstract pathname should be included in a pathname list.
It returns true
if and only if pathname should be included in the list.
2. How to Use FileFilter
The best way to use the FileFilter
is to pass it to listFiles()
method in File
class where File represents a directory location.
3. FileFilter Example
3.1. Filtering all matching files in the specified directory
In the given Java example, we are finding all the log files from the "c:/temp"
directory.
The above program will list down all .log
files present in c:/temp
folder.
3.2. Creating FileFilter with Lambda Expression
The given program uses the lambda expression syntax to create the FileFilter instance. Rest all the operations will be the same.
Happy Learning !!
Comments