Depth Control and maxDepth Parameter
You'll learn how to limit how deep Files.walk explores into subdirectories.
Understanding Traversal Depth
When walking a file tree with Files.walk, you might not always want to explore every subdirectory all the way down. Imagine a folder structure like a family tree—sometimes you only want to see children and grandchildren, not every descendant going back generations.
The maxDepth parameter lets you control exactly how many levels deep the walk should go. A depth of 1 means only the starting directory itself. A depth of 2 includes the starting directory plus its immediate children. Each level deeper adds another layer of subdirectories.
How maxDepth Works
// Visit only the starting directory (depth 1)
Files.walk(startPath, 1)
.forEach(System.out::println);
// Visit the directory and its immediate children (depth 2)
Files.walk(startPath, 2)
.forEach(System.out::println);
// Visit directory, children, and grandchildren (depth 3)
Files.walk(startPath, 3)
.forEach(System.out::println);
The depth counts from the starting path as level 1. Each subdirectory level increments the depth by one.
Practical Example
Path projectRoot = Paths.get("/projects/myapp");
// List only top-level files and folders
try (Stream<Path> shallow = Files.walk(projectRoot, 1)) {
shallow.filter(Files::isDirectory)
.forEach(System.out::println);
}
// Include files two levels deep
try (Stream<Path> deeper = Files.walk(projectRoot, 2)) {
deeper.filter(Files::isRegularFile)
.forEach(System.out::println);
}
Key Takeaway: Use the maxDepth parameter in Files.walk to control traversal depth, preventing unnecessary exploration of deeply nested directories and improving performance when you only need surface-level information.