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 theaccept
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:
FileFilter.java
package com.javacodegeeks.java.core; import java.io.File; import java.io.FilenameFilter; public class FileFilter implements FilenameFilter { private String fileExtension; public FileFilter(String fileExtension) { this.fileExtension = fileExtension; } @Override public boolean accept(File directory, String fileName) { return (fileName.endsWith(this.fileExtension)); } }
DeleteTextFiles.java
package com.javacodegeeks.java.core; import java.io.File; 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!"); return; } 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(); System.out.println(absoluteFilePath); } } }
Output:
I found these files with .txt extension:
C:\Users\nikos7\Desktop\files\file1.txt
C:\Users\nikos7\Desktop\files\file2.txt
C:\Users\nikos7\Desktop\files\file3.txt
C:\Users\nikos7\Desktop\files\file4.txt
C:\Users\nikos7\Desktop\files\file5.txt
This was an example on how to list files with certain extension only using FilenameFilter in Java.