A directory is a File that contains a list or other files and directories. When you create a. File object and it is a directory, the Directory( ) method will return true. In this case, you can roll stf ) on the object to extract the list of other files and directories inside; It has two forms. The thirst is shown here:

String] ] list( )

The list of  files is returned in .111 array of String objects'.

The program shown here illustrates how to use list( ) to examine the contents of n directory:

Here is sample output from the program. (Of course, the output you see will be different, based on what is in your directory.)

Directory of /java
bin is a directory
lib is a directory
d~mo is a directory
COPYRIGHT is a file
README is a file
index.html is a file
include is a directory is a file .
.hotjava is a directory
src is a directory

Using Filename Filter

You Will often want to limit the number of files returned by the list( ) method to include only those files that n~tch a certain filename pattern, or feWer. 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 Fllenamcl'Iltcr interface. Panama Filter 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, Stringfilename)

TIle accept() method returns true {or 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.

Til  Fixation class, shown next, implements Filenamefilter. It will be used to modify till preceding program 1 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.

The modified directory listing program is shown here. Now it will only display files that use the .html extension.

Share This