Walking Directory Trees with Files.walk
Recursively list files, filter by extension, and compute directory sizes with Files.walk.
Files.walk Overview
Files.walk(startPath) returns a lazy Stream<Path> that recursively lists all files and directories starting from the given path. Depth-first traversal, includes the start path itself.
import java.nio.file.*;
import java.util.stream.*;
try (Stream<Path> stream = Files.walk(Path.of("/home/user/projects"))) {
stream.forEach(System.out::println);
} // stream and underlying resources closed automaticallyLimiting Depth
Provide a max depth to prevent deep recursion:
Path root = Path.of("/home/user/projects");
// Only immediate children (depth 1)
try (var stream = Files.walk(root, 1)) {
stream.filter(p -> !p.equals(root)) // exclude start path
.forEach(System.out::println);
}All lessons in this course
- Path: Representing File Locations
- Files Utility: Read, Write, Copy, Move
- Walking Directory Trees with Files.walk
- WatchService: Monitoring File Changes