0Pricing
Java Academy · Lesson

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 automatically

Limiting 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

  1. Path: Representing File Locations
  2. Files Utility: Read, Write, Copy, Move
  3. Walking Directory Trees with Files.walk
  4. WatchService: Monitoring File Changes
← Back to Java Academy