Here is sample output from the program. (Of course, the output you see will be different,
based on what is in the directory.)
Directory of /java
bin is a directory
lib is a directory
demo is a directory
COPYRIGHT is a file
README is a file
index.html is a file
include is a directory
src.zip is a file
src is a directory
Using FilenameFilter
You will often want to limit the number of files returned by the list( ) method to include
only those files that match a certain filename pattern, or filter. To do this, you must use a
second form of list( ), shown here:
String[ ] list(FilenameFilter FFObj)
In this form, FFObj is an object of a class that implements the FilenameFilter interface.
FilenameFilter defines only a single method, accept( ), which is called once for each file
in a list. Its general form is given here:
boolean accept(File directory, String filename)
The accept( ) method returns true for files in the directory specified by directory that should
be included in the list (that is, those that match the filename argument), and returns false for
those files that should be excluded.
The OnlyExt class, shown next, implements FilenameFilter. It will be used to modify
the preceding program so that it restricts the visibility of the filenames returned by list( )
to files with names that end in the file extension specified when the object is constructed.
import java.io.*;
public class OnlyExt implements FilenameFilter {
String ext;
public OnlyExt(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name) {
return name.endsWith(ext);
}
}
The modified directory listing program is shown here. Now it will only display files that use
the .html extension.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home