In this section, you will learn how to filter files.
Some times you want to retrieve a specific subset of files and discard unnecessary files, this is said to be filtering the files. The interface FilenameFilter provides the logic of filtering. It will display a list of files with some of the files filtered out.
In the given example, we have created a class that implements java.io.FilenameFilter and code the method accept(). Then we have called the method list() through the object of File class and pass filter as a parameter. The returned array of strings has all the file names that passed through the accept() method.
list(): This method of File class lists all the files in a directory.
FilenameFilter: This is an interface which can be used to get only the set of files that match a specific criteria.
Here is the code:
import java.io.*;
public class FileFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return name.endsWith("jpg");
}
public static void main(String args[]) throws Exception {
File f = new File("c:/");
FilenameFilter filter = new FileFilter();
String s[] = f.list(filter);
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}
}
}
Through the above code, you can filter your files and retrieve a specific subset of files.
Output:
|
barbie.jpg |