Java Files  «Prev  Next»
Lesson 10Listing directories and paths
ObjectiveWrite a program that recursively lists all the files in a directory.

List all Files

Listing directories

This method returns null if the File object does not point to a directory. It throws a security exception if the program isn't allowed to read the directory being listed.
The list() method returns an array of Strings initialized to the names of each file in a directory. It is useful for processing all the files in a directory.

public String[] list()

There's also an alternative version of list() that is the same as the previous method except you can use a FilenameFilter object to restrict which files are included in the list.
The alternative version of list() uses a FilenameFilter object to restrict which files are included in the list:

public String[] list(FilenameFilter filter)

listFiles() methods

The two list() methods return arrays of strings and the strings contain the names of files.
You can use these to construct File objects. Java 2 allows you to eliminate the intermediate step of creating File objects by providing two listFiles() methods that return arrays of File objects instead of arrays of strings.

public File[] listFiles() // Java 2
public File[] listFiles(FilenameFilter filter) // Java 2
public File[] listFiles(FileFilter filter) // Java 2

The no-argument variant of listFiles() simply returns an array of all the files in the given directory. The other two variants return the files that pass through their filters. File and filename filters will be discussed shortly.

File URLs

File URLs are used inside web browsers to refer to a file on the local hard drive.[3] They have the basic form:

file://  <host> /<path>

<host> should be the fully qualified domain name of the system on which the is found, though if it is omitted, the local host is assumed. <path> is the hierarchical path to the file, using a forward slash as a directory separator (regardless of host filename conventions) and URL encoding of any special characters in filenames that would normally be encoded in a URL. Examples of file URLs include:

file:///C|/docs/JCE%201.2%20beta%201/guide/API_users_guide.html
file:///usr/local/java/docs/JCE%201.2%20beta%201/guide/API_users_guide.html
file:///D%7C/JAVA/

Working With Directories Paths - Exercise

Click the Exercise link below to write a program that recursively lists all the files in a directory, all the files in any directories in that directory, all the files in successive directories.
Working With Directories Paths - Exercise