Java Reference
In-Depth Information
The only distinction between these two is the parameter list for the method in the interfaces. The
accept()
method in the
FilenameFilter
class has two parameters for you to specify the directory
plus the file name to identify a particular file, so this is clearly aimed at testing whether a given file
should be included in a list of files. The
accept()
method for the
FileFilter
interface has just a
single parameter of type
File
, this is used to filter files and directories.
The filtering of the list is achieved by the
list()
or
listFiles()
method by calling the method
accept()
for every item in the raw list. If the method returns
true
, the item stays in the list, and if it
returns
false
, the item is not included. Obviously, these interfaces act as a vehicle to allow the
mechanism to work, so you need to define your own class that implements the appropriate interface. If
you are using
the
list()
method, your class must implement the
FilenameFilter
interface. If you
are using the
listFiles()
method, you can implement either interface. How you actually filter the
filenames is entirely up to you. You can arrange to do whatever you like within the class that you
define. We can see how this works by extending the previous example a little further.
Try It Out - Using the FilenameFilter Interface
We can define a class to specify a file filter as:
import java.io.File;
import java.io.FilenameFilter;
import java.util.Date; // For the Date class
public class FileListFilter implements FilenameFilter {
private String name; // File name filter
private String extension; // File extension filter
// Constructor
public FileListFilter(String name, String extension) {
this.name = name;
this.extension = extension;
}
public boolean accept(File directory, String filename) {
boolean fileOK = true;
// If there is a name filter specified, check the file name
if (name != null)
fileOK &= filename.startsWith(name);
// If there is an extension filter, check the file extension
if (extension != null)
fileOK &= filename.endsWith('.' + extension);
return fileOK;
}
}
This uses the methods
startsWith()
and
endsWith()
, which are defined in the
String
class that
we discussed in Chapter 4. Save this source in the same directory as the previous example, as
FileListFilter.java
.