Java FilenameFilter to Find Files Matching Pattern

Many times we need to traverse and find all files with a certain name pattern to do some operations on those files, for example deleting those files. This is more often required when we want to delete all .log or .tmp files from the server after a certain time using the application (if such a requirement exists).

In Java, we can use FilenameFilter class. It tests if a specified file should be included in a file list. To use FilenameFilter, override the accept(dir, name) method that contains the logic to check if the file has to be included in the filtered list.

1. Java FilenameFilter

From Java 8 onwards, FileNameFilter is a functional interface. The classes that implement this interface are used to filter filenames. It has a single method accept() that takes two parameters:

  • dir: directory in which the file was found
  • name: the file name

The given LogFilterFilter class can be used to filter all log files from a list of files.

public class LogFilterFilter implements FilenameFilter
{
  @Override
  public boolean accept(File dir, String fileName)
  {
    return fileName.endsWith(".log");
  }
}

2. How to use FilenameFilter

The best way to use the FileNameFilter is to pass it to one of the following methods in java.io.File class where File represents a directory location:

  • String[] list(filter) : returns an array of strings naming the files and directories in the target directory.
  • File[] listFiles(filter) : returns an array of files and directories in the target directory.

3. FilenameFilter Examples

Let us look at a few examples to understand how we can use the FilenameFilter class.

Example 1: Java program to use FilenameFilter to find all log files

In this example, we will use FilenameFilter instance to list out all ".log" files in folder "c:/temp". We will also delete all these log files.

String targetDirectory = "c:\\temp";
File dir = new File(targetDirectory);

//Find out all log files
String[] logFiles = dir.list(new LogFilterFilter());

//If no log file found; no need to go further
if (logFiles.length == 0)
  return;

//This code will delete all log files one by one
for (String fileName : logFiles)
{
  String logFile = new StringBuffer(targetDirectory)
      .append(File.separator)
      .append(fileName)
      .toString();

  Files.delete(Paths.get(logFile));
  System.out.println("Log file : " + logFile + " is deleted");
}

Example 2: Creating FilenameFilter using Lambda Expression

Since FileNameFilter is a functional interface, we can reduce and create it using a lambda expression.

FilenameFilter logFileFilter = (d, s) -> {
  return s.toLowerCase().endsWith(".log");
};

String[] logFiles = dir.list(logFileFilter);

Example 3: Creating FilenameFilter containing Regular Expressions

This Java program filters all files based on file names matching a regular expression. For example, we want to list all the files that do not contain a number in their names.

FilenameFilter filter = (d, s) -> {
  return s.matches("[a-zA-z]+\\.[a-z]+");
};

String[] filteredFiles = dir.list(filter);

4. Conclusion

In this Java tutorial, we learned to use the FilenameFilter to traverse a directory and search all files with names matching a specified pattern.

Happy Learning !!

Source Code on Github

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.