Java FileFilter (with Examples)

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.

FileFilter logFilefilter = new FileFilter()
{
	public boolean accept(File file) {
		if (file.getName().endsWith(".log")) {
			return true;
		}
		return false;
	}
};

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.

File directory = new File("/path/directory");

File[] files = directory.listFiles(logFilefilter);

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.

File directory = new File("c:/temp");

//Verify if it is a valid directory
if (!(directory.exists() && directory.isDirectory()))
{
  System.out.println(String.format("Directory %s does not exist", directory));
  return;
}

FileFilter logFilefilter = new FileFilter() {
  public boolean accept(File file) {
    if (file.getName().endsWith(".log")) {
      return true;
    }
    return false;
  }
};

File[] files = directory.listFiles(logFilefilter);

for (File f: files)
{
  System.out.println(f.getName());
}

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.

FileFilter logFileFilter = (file) -> {
  return file.getName().endsWith(".log");
};

File[] files = directory.listFiles(logFilefilter);	

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode