Share on Google+Share on Google+

Java file filter

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 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:


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++) {

Through the above code, you can filter your files and retrieve a specific subset of files.




Posted on: April 27, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.


Advertisement null