Java FilenameFilter Example

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 certain time using the application (if such requirement exist).

In Java, we can use FilenameFilter class and override its accept(File targetDirectoty, String fileName) method, to perform the file filtering on all files inside the target directory.

1. Java FilenameFilter class

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:

/**
* Parameters:
*   dir - the directory in which the file was found.
* 	name - the name of the file.
* Returns:
*	true if and only if the name should be included in the file list; false otherwise.
*/

boolean	accept(File dir, String name)

2. Using FilenameFilter with File class

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

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

3. Java FilenameFilter Example

Lets look at 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.

import java.io.File;
import java.io.FilenameFilter;

public class FilenameFilterExample 
{
	public static void main(String[] args) 
	{
		//Delete all files from this directory
		String targetDirectory = "c:\\temp";
		File dir = new File(targetDirectory);

		//Filter 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 log : logFiles) 
		{
			String tempLogFile = new StringBuffer(targetDirectory).append(File.separator).append(log).toString();
			File fileDelete = new File(tempLogFile);
			boolean isdeleted = fileDelete.delete();
			System.out.println("file : " + tempLogFile + " is deleted : " + isdeleted);
		}
	}
}

//This filter will be used to check for all files if a file is log file
class LogFilterFilter implements FilenameFilter 
{
	@Override
	public boolean accept(File dir, String fileName) 
	{
		return (fileName.endsWith(".log"));
	}
}

Example 2: Java program to create FilenameFilter using Lambda expression

Since FileNameFilter is a functional interface, we can reduce create it using a lambda expression. Then the whole example is shrunk to given below the shorter version.

import java.io.File;
import java.io.FilenameFilter;

public class FilenameFilterExample 
{
	public static void main(String[] args) 
	{
		//Delete all files from this directory
		String targetDirectory = "c:\\temp";
		File dir = new File(targetDirectory);

		//Filter out all log files
		String[] logFiles = dir.list((d, s) -> {
			return s.toLowerCase().endsWith(".log");
		});

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

		//Process all files as needed
	}
}

Example 3: Java FilenameFilter Regex Example

Java program to filter 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.

import java.io.File;
import java.io.FilenameFilter;

public class FilenameFilterExample 
{
	public static void main(String[] args) 
	{
		//Delete all files from this directory
		String targetDirectory = "c:\\temp";
		File dir = new File(targetDirectory);

		//Filter out all log files
		String[] logFiles = dir.list((d, s) -> {
			return s.matches("[a-zA-z]+\\.[a-z]+");
		});

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

		//Process all files as needed
	}
}

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.