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 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");

		File f = new File("c:/");
		FilenameFilter filter = new FileFilter();
		String s[] = f.list(filter);

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
