Java Reference
In-Depth Information
Listing a Directory
Problem
You need to list the filesystem entries named in a directory.
Solution
Use a
java.io.File
object's
list()
or
listFiles()
method.
Discussion
The
java.io.File
class contains several methods for working with directories. For ex-
ample, to list the filesystem entities named in the current directory, just write:
String[] list = new File(".").list( )
To get an array of already constructed
File
objects rather than
String
s, use:
File[] list = new File(".").listFiles( );
This can become a complete program with as little as the following:
public
public class
class
LLs
{
public
public static
void
main
(
String args
[]) {
String
[]
dirs
=
new
static
void
new
java
.
io
.
File
(
"."
).
list
();
// Get list of names
Arrays
.
sort
(
dirs
);
// Sort it (see <<javacook-structure-SECT-8>>)
for
for
(
String dir
:
dirs
) {
System
.
out
.
println
(
dir
);
// Print the list
}
}
}
Of course, there's lots of room for elaboration. You could print the names in multiple
columns across the page. Or even down the page because you know the number of items in
the list before you print. You could omit filenames with leading periods, as does the Unix
ls
program. Or print the directory names first; I once used a directory lister called
lc
that did