Filename Filters

You often want to look for a particular kind of filefor example, text files. To do this, you need a FilenameFilter object that specifies which files you'll accept. FilenameFilter is an interface in the java.io package:

public interface FilenameFilter

This interface declares a single method, accept( ):

public abstract boolean accept(File directory, String name);

The directory argument is a File object pointing to a directory, and the name argument is the name of a file. The method should return true if a file with this name in this directory passes through the filter and false if it doesn't. Example 17-7 is a class that filters out everything that is not an HTML file.

Example 17-7. HTMLFilter

import java.io.*; public class HTMLFilter implements FilenameFilter { public boolean accept(File directory, String name) { if (name.endsWith(".html")) return true; if (name.endsWith(".htm")) return true; return false; } }

Files can be filtered using any criteria you like. An accept( ) method may test modification date, permissions, file size, and any attribute Java supports. This accept( ) method tests whether the file ends with .html and is in a directory where the program can read files:

public boolean accept(File directory, String name) { if (name.endsWith(".html") && directory.canRead( )) { return true; } return false; }

Filename filters are primarily intended for the use of file dialogs, which will be discussed in the next chapter. However, the listFiles( ) method can take a FilenameFilter as an argument:

public File[] listFiles(FilenameFilter filter)

This method assumes that the File object represents a directory. The array of File objects returned by listFiles( ) only contains those files that passed the filter. For example, the following lines of code list HTML files in the /public/html/javafaq directory using the HTMLFilter of Example 17-7:

File dir = new File("/public/html/javafaq"); File[] htmlFiles = dir.listFiles(new HTMLFilter( )); for (int i = 0; i < htmlFiles.length; i++) { System.out.println(htmlFiles[i]); }

Категории