Files.walk: Stream-Based Directory Traversal
What you'll learn: How to use Files.walk() to traverse entire directory trees efficiently using Java's Stream API.
The Core Idea
Files.walk() creates a Stream<Path> that lazily walks through a directory structure, visiting every file and subdirectory within it. Unlike Files.list() which only reads entries in a single directory, Files.walk() descends into subdirectories recursively, giving you access to the entire file tree.
Think of it like exploring a building: Files.list() shows you what's on one floor, while Files.walk() takes you through every floor and room in the entire building.
Basic Usage
Path startDir = Paths.get("myFolder");
try (Stream<Path> paths = Files.walk(startDir)) {
paths.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
This code prints every file and directory starting from myFolder, including all nested contents.
Controlling Depth
You can limit how deep the traversal goes:
// Only visit the starting directory and one level down
try (Stream<Path> paths = Files.walk(startDir, 1)) {
paths.forEach(System.out::println);
}
Depth 0 means only the starting directory itself. Depth 1 includes immediate children. Depth 2 includes grandchildren, and so on.
Filtering the Stream
Since Files.walk() returns a Stream<Path>, you can use stream operations:
try (Stream<Path> paths = Files.walk(startDir)) {
paths.filter(Files::isRegularFile)
.filter(p -> p.toString().endsWith(".txt"))
.forEach(System.out::println);
}
This finds all .txt files in the entire tree.
Key Takeaway: Files.walk() provides stream-based recursive directory traversal with optional depth control, enabling powerful file tree operations using familiar Stream API methods.