Sub topic 14
Walking Directory Trees in Java
This chapter assumes you know Path, Files, checked exceptions, and Java streams. A directory tree is a directory and all files and subdirectories below it. Java NIO lets you inspect that tree without manually writing recursive directory logic.
Choosing a tree-walking API
The Files class provides two common approaches:
| API | Best for | Result |
|---|---|---|
| `Files.walk` | Filtering or collecting paths with streams | `Stream<Path>` |
| `Files.walkFileTree` | Custom actions during traversal | Visitor callbacks |
Files.walk is usually the simplest choice when you want to find files. It starts at a root path and produces paths below that root.
Finding files with Files.walk
The following program searches the current directory and prints every regular file whose name ends with .txt.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class FindTextFiles {
public static void main(String[] args) throws IOException {
Path root = Path.of(".");
try (Stream<Path> paths = Files.walk(root)) {
paths.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(".txt"))
.forEach(System.out::println);
}
}
}Files.isRegularFile removes directories from the result. The second filter selects text files by their filename suffix. The stream is lazy, so paths are discovered as the stream is consumed instead of being loaded into a list first.
The try block matters. The stream owns an open directory resource, so try-with-resources closes it even when traversal or processing fails.
You can limit traversal depth by passing a second argument:
try (Stream<Path> paths = Files.walk(Path.of("."), 2)) {
paths.forEach(System.out::println);
}A depth of 0 visits only the root. A depth of 1 also visits its immediate children. This can prevent an accidental scan of a very large tree.
Handling errors during traversal
Files.walk can throw an IOException when it cannot open the root or read part of the tree. A permission problem in one directory can therefore interrupt the stream. Catch the exception when the application should report the problem or continue with another operation.
Symbolic links are not followed by default. This avoids repeatedly visiting paths when links form cycles. If you deliberately need to follow links, use the overload that accepts FileVisitOption.FOLLOW_LINKS, and consider the risk of cycles and unexpected files.
When to use walkFileTree
Use Files.walkFileTree when each directory or file needs a custom action, such as deleting a tree, calculating totals, or handling failures per path. It uses a FileVisitor<Path> with callbacks such as visitFile and preVisitDirectory. For simple filtering, Files.walk is shorter and works naturally with stream operations.
Exercise
Why must a stream returned by Files.walk usually be used inside try-with-resources?
Show answer
The stream holds directory resources while it traverses the tree, so try-with-resources closes those resources reliably.