Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
// 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 thelist( )method, calledlistFiles( ), which you might find useful.
The signatures forlistFiles( )are shown here:

File[ ] listFiles( )
File[ ] listFiles(FilenameFilterFFObj)
File[ ] listFiles(FileFilterFObj)

These methods return the file list as an array ofFileobjects instead of strings. The first method
returns all files, and the second returns those files that satisfy the specifiedFilenameFilter.
Aside from returning an array ofFileobjects, these two versions oflistFiles( )work like their
equivalentlist( )methods.
The third version oflistFiles( )returns those files with path names that satisfy the specified
FileFilter.FileFilterdefines only a single method,accept( ), which is called once for each file in a
list. Its general form is given here:

boolean accept(Filepath)

Theaccept( )method returnstruefor files that should be included in the list (that is, those
that match thepathargument), andfalsefor those that should be excluded.

Creating Directories

Another two usefulFileutility methods aremkdir( )andmkdirs( ). Themkdir( )method
creates a directory, returningtrueon success andfalseon failure. Failure indicates that the
path specified in theFileobject 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 themkdirs( )
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 tojava.io:Closeableand
Flushable. The interfaces areimplemented 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.

Chapter 19: Input/Output: Exploring java.io 561

Free download pdf