Java FilenameFilter Interface
How to use Java FilenameFilter with File.list to filter file names
The FilenameFilter interface is used for filtering when you want to obtain only lists that contain specific file names in the system, and it is passed as an argument to the list() method of the File class.
FilenameFilter Method
| Method | Description |
|---|---|
boolean accept(File dir, String name) |
Receives the directory path (dir) and file name (name). |
The FilenameFilter interface has only one method, accept(), which is called once for each file in the list. You must override the accept() method for the files you want to filter. Return true for file names you want to include in filtering, and return false for file names you want to exclude.
FilenameFilter Example
The following example receives a directory and displays file names that end with .java.
package com.devkuma.tutorial.java.io;
import java.io.File;
import java.io.FilenameFilter;
class JavaFilenameFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return name.endsWith(".java");
}
}
public class FilenameFilterInterface {
public static void main(String[] args) {
File file = new File("src/main/java/com/devkuma/tutorial/javaio");
JavaFilenameFilter filter = new JavaFilenameFilter();
for (String path : file.list(filter)) {
System.out.println(path);
}
}
}
Output:
FileClass.java
FilenameFilterInterface.java