Java source code examples

Java source code samples. Java code examples.

Creating a FileFilter

1 votes Vote!!

Creating a FileFilter

We need to implement the FileFilter class for creating a file filter. The FileFilter interface contains only one method accept(File). This method is used for checking whether a file should be included or excluded.

import java.io.File;
import java.io.FilenameFilter;
/**
 *
 * A file filter.
 *
 */
class TextFileFilter implements FileFilter {
	/**
	 * Pattern would contain the extension of
	 * the file.
	 */
	private String pattern;

	/**
	 * Initializes the pattern.
	 *
	 * Provide the file extension to filter.
	 *
	 * @param pattern
	 */
	public TextFileFilter(String pattern){
		this.pattern  = pattern;
	}

	public boolean accept(File pathname) {
		return pathname.getName().endsWith(this.pattern);
	}

}
}

To invoke the above FileFilter create an object of the TextFileFilter class like

	TextFileFilter  filter = new TextFileFilter("txt");

The argument to TextFileFilter will be the extension of the file we need to include.

  • Share/Bookmark

Tags: java.io

Discuss This Code