img
// Directory of .HTML files.
import java.io.*;
class DirListOnly {
public static void main(String args[]) {
String dirname = "/java";
File f1 = new File(dirname);
FilenameFilter only = new OnlyExt("html");
String s[] = f1.list(only);
for (int i=0; i < s.length; i++) {
System.out.println(s[i]);
}
}
}
The listFiles( ) Alternative
There is a variation to the list( ) method, called listFiles( ), which you might find useful.
The signatures for listFiles( ) are shown here:
File[ ] listFiles( )
File[ ] listFiles(FilenameFilter FFObj)
File[ ] listFiles(FileFilter FObj)
These methods return the file list as an array of File objects instead of strings. The first method
returns all files, and the second returns those files that satisfy the specified FilenameFilter.
Aside from returning an array of File objects, these two versions of listFiles( ) work like their
equivalent list( ) methods.
The third version of listFiles( ) returns those files with path names that satisfy the specified
FileFilter. FileFilter 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 path)
The accept( ) method returns true for files that should be included in the list (that is, those
that match the path argument), and false for those that should be excluded.
Creating Directories
Another two useful File utility methods are mkdir( ) and mkdirs( ). The mkdir( ) method
creates a directory, returning true on success and false on failure. Failure indicates that the
path specified in the File object already exists, or that the directory cannot be created because
the entire path does not exist yet. To create a directory for which no path exists, use the mkdirs( )
method. It creates both a directory and all the parents of the directory.
The Closeable and Flushable Interfaces
Recently (with the release of JDK 5), two interfaces were added to java.io: Closeable and
Flushable. The interfaces are implemented by several of the I/O classes. Their inclusion
does not add new functionality to the stream classes. They simply offer a uniform way of
specifying that a stream can be closed or flushed.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home