Java Reference
In-Depth Information
20.7.4.
FilenameFilter
and
FileFilter
The
FilenameFilter
interface provides objects that filter unwanted files
from a list. It supports a single method:
boolean
accept(File dir, String name)
Returns
true
if the file named
name
in the directory
dir
should
be part of the filtered output.
Here is an example that uses a
FilenameFilter
object to list only direct-
ories:
import java.io.*;
class DirFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return new File(dir, name).isDirectory();
}
public static void main(String[] args) {
File dir = new File(args[0]);
String[] files = dir.list(new DirFilter());
System.out.println(files.length + " dir(s):");
for (String file : files)
System.out.println("\t" + file);
}
}
First we create a
File
object to represent a directory specified on the
command line. Then we create a
DirFilter
object and pass it to
list
.
For each name in the directory,
list
invokes the
accept
method on the
filtering object and includes the name in the list if the filtering object