h1

Java Titbits – Filtering files

July 8, 2010

We 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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: