Listing the Immediate Entries in a Directory – Java I/O: Part II

Listing the Immediate Entries in a Directory

A common file operation is to list the entries in a directory, similar to basic usage of the DOS command dir or the Unix command ls. The list() method of the Files class creates a stream whose elements are Path objects that denote the entries in a directory.

Click here to view code image

static Stream<Path> list(Path dir) throws IOException

Creates a lazily populated Stream whose elements are the entries in the directory—it does not recurse on the entries of the directory. The stream does not include the directory itself or its parent. It throws a java.nio.file.NotDirectoryException if it is not a directory (optional specific exception). Also, it does not follow symbolic links.

The following code lists the entries under the directory a. Note that the stream only contains the immediate entries in the directory. Any subdirectories under the specified directory are not traversed. The Path object passed a parameter must denote a directory, or a disgruntled NotDirectoryException is thrown.

Click here to view code image

Path dir = Path.of(“.”, “a”);
System.out.printf(“Immediate entries under directory \”%s\”:%n”, dir);
try(Stream<Path> stream = Files.list(dir)) {
  stream.forEach(System.out::println);
} catch (NotDirectoryException nde) {
nde.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}

Output from the code:

Click here to view code image

Immediate entries under directory “./a”:
./a/x.txt
./a/b

File Visit Option

In the file operations we have seen so far, the default behavior was to follow symbolic links. Not so in the case of the traversal methods find() and walk() of the Files class—these methods do not follow symbolic links, unless instructed explicitly to do so. The FileVisitOption enum type defines the constant FOLLOW_LINKS (Table 21.13) that can be specified to indicate that symbolic links should be followed when using these methods.

Table 21.13 File Visit Option

Enum java.nio.file.FileVisitOption constantDescription
FOLLOW_LINKSIndicates that symbolic links should be followed.

Leave a Reply

Your email address will not be published. Required fields are marked *