Junior
What can you tell about the FileFilter interface?
sobes.tech AI
Answer from AI
FileFilter is a functional interface in the java.io package used for filtering files based on specified criteria. It has one abstract method: boolean accept(File pathname).
Method signature:
// Checks if the specified abstract pathname is accepted.
boolean accept(File pathname);
The accept(File pathname) method returns true if the file or directory represented by the pathname object meets the filter criteria, and false otherwise.
FileFilter is often used in methods that work with file lists, such as:
list(FileFilter filter)in theFileclass.listFiles(FileFilter filter)in theFileclass.
Example of filtering only files (excluding directories):
import java.io.File;
import java.io.FileFilter;
public class OnlyFilesFilterExample {
public static void main(String[] args) {
File dir = new File("."); // Current directory
// Create a FileFilter to accept only files
FileFilter onlyFilesFilter = new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile(); // Returns true if it is a file
}
};
// Use the filter to get the list of files
File[] fichiers = dir.listFiles(onlyFilesFilter);
if (fichiers != null) {
for (File fichier : fichiers) {
System.out.println(fichier.getName());
}
}
}
}
Using lambda expressions (available from Java 8, as FileFilter is a functional interface):
import java.io.File;
import java.io.FileFilter;
public class LambdaFileFilterExample {
public static void main(String[] args) {
File dir = new File("."); // Current directory
// Use a lambda expression as a FileFilter
File[] directories = dir.listFiles(pathname -> pathname.isDirectory()); // Filter for directories
if (directories != null) {
for (File directory : directories) {
System.out.println(directory.getName());
}
}
}
}
FileFilter allows creating reusable filtering criteria for working with the file system.