Home Tutorial Java Core Files Java file filter

 
 

Share on Google+Share on Google+
Java file filter
Posted on: April 27, 2006 at 12:00 AM
Advertisement
In this section, you will learn how to filter files.

Java file filter

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
image.jpg
img.jpg
new.jpg
node.jpg
rose.jpg
screen.jpg

Advertisement

Related Tags for Java file filter:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 27, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com