HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Java FilenameFilter Example

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces