Find files with certain extension only using FilenameFilter in Java

In this tutorial we are going to show you how to use the FilenameFilter interface in Java in order to list all the file with a certain property in their names. In this example for instance, we just want to print all the text files in a specific directory, hence the files ending with the “.txt” extension. Instances of classes that implement this interface are used to filter file names. These instances are used to filter directory listings in the list method of class File.

In short to delete files with certain extensions using FilenameFilter you have to:

  • Create a class that implements the FilenameFilter interface and override the accept method to perform the filtering you want in the filename.
  • Use the above class as the argument in the list method, when listing the files of the target directory.

So here is the FileFilter class the implements FilenameFilter interface:



public class FileFilter implements FilenameFilter {

	private String fileExtension;

	public FileFilter(String fileExtension) {
		this.fileExtension = fileExtension;

	public boolean accept(File directory, String fileName) {
		return (fileName.endsWith(this.fileExtension));



public class FindTextFiles {

	private static String parentDirectory = "C:\\Users\\nikos7\\Desktop\\files";
	private static String fileExtension = ".txt";

	public static void main(String[] args) {
		FileFilter fileFilter = new FileFilter(fileExtension);
		File parentDir = new File(parentDirectory);

		// Put the names of all files ending with .txt in a String array
		String[] listOfTextFiles = parentDir.list(fileFilter);

		if (listOfTextFiles.length == 0) {
			System.out.println("There are no text files in this direcotry!");

		System.out.println("I found these files with "+fileExtension+" extension:");

		for (String file : listOfTextFiles) {

			//construct the absolute file paths...
			String absoluteFilePath = new StringBuffer(parentDirectory).append(File.separator).append(file).toString();



I found these files with .txt extension:

This was an example on how to list files with certain extension only using FilenameFilter in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button