List all the contents of a directory according to a filter.
The list method of File class can be used for listing all the contents of a directory according to a filter.
import java.io.File;
import java.io.FilenameFilter;
/**
* File class examples
*/
public class FileExample {
public static void main(String[] args){
// Create file object representing the directory
File file = new File("d:\\temp");
// Create a FilenameFilter for filtering all the text files.
FileFilter filter = new FileFilter("txt");
// List the contents of the directory.
String contents[] = file.list(filter);
// Loop through the array and display the file/directory names.
for (int i = 0; i < contents.length; i++) {
System.out.println(contents[i]);
}
}
}
/**
*
* A file filter.
*
*/
class FileFilter implements FilenameFilter{
/**
* Pattern would contain the extension of
* the file.
*/
private String pattern;
/**
* Initializes the pattern.
*
* Provide the file extension to filter.
*
* @param pattern
*/
public FileFilter(String pattern){
this.pattern = pattern;
}
public boolean accept(File dir, String name) {
return name.endsWith(this.pattern);
}
}
The above examples filters out all the non text files from the directory. The list method returns an array of file names that matches the filter. But if we want an array of File objects instead of file names we should use listFiles method instead of list method.




















