You often want to look for a particular kind of file—for
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. Because FilenameFilter
is an
interface, it must be implemented in a class. Example 12.6 is a class
that
filters out everything that is not an HTML file.
Files can be filtered using any criteria you like. An
accept()
method may test modification date,
permissions, file size, and any attribute Java supports. (You
can’t filter by attributes Java does not support, like
Macintosh file and creator codes, at least not without native methods
or some sort of access to the native API.) 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, in Java 2 the
File
class has a listFiles()
method that takes a FilenameFilter
as an argument:
public File[] listFiles(FilenameFilter filter) // Java 2
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 12.6.
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]); }
18.189.31.26