
Java Titbits – Filtering files
July 8, 2010We would have encountered scenarios where we would want to filter certain files within a directory. The traditional method is to get all the files and run through that list and select those that you need. But java does provide a fileNamefilter class or a fileFilter class that you can use while listing all the files within a directory. (And this has been in jdk since version 1.0 .. something that i didnt know.)
An example to filter all jpeg files in a directory C:\pictures
File myDir = new File(“C:/pictures”);
File[] contents = myDir.listFiles(new FileNameFilter() {
public boolean accept(File directory, String fileName) {
return (fileName.endswith(“jpeg”));
}
} );
You can also use FileFilter if the accept method needs to use any attributes of file object.
