Directory Operations

Although most of the methods in the File class can be used on both files and directories, the list method is only for use in a directory:

public String[] list()

The list method returns an array of the names of all the files contained within the directory. You can also set up a filename filter for the list method, which enables you to select only certain filenames:

public String[] list(FilenameFilter filter)

The FilenameFilter interface defines a single method, accept, that returns true if a filename should be included in the list:

public abstract boolean accept(File dir, String name)

Listing 21.7 shows an object that implements a filename filter that allows only files ending with .java.

Code Listing 21.7. ...

Get Special Edition Using Java 2 Standard Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.