Java

Files.walk — Recursive Tree Traversal

admin by @admin ADMIN
15m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`Files.walk` returns a lazy Stream over every entry under a path. Filter with stream operations; remember to close the stream (or use try-with-resources).
Java
Raw
import java.io.IOException;
import java.nio.file.*;
import java.util.stream.Stream;

class Demo {
    void example() throws IOException {
        // Every .java file under src/
        try (Stream<Path> stream = Files.walk(Path.of("src"))) {
            stream
                .filter(Files::isRegularFile)
                .filter(p -> p.toString().endsWith(".java"))
                .forEach(System.out::println);
        }

        // Count files
        try (var s = Files.walk(Path.of("."))) {
            long count = s.filter(Files::isRegularFile).count();
            System.out.println("file count: " + count);
        }

        // Limit depth
        try (var s = Files.walk(Path.of("."), 2)) {
            s.forEach(System.out::println);
        }

        // Use Files.find when you want a predicate that gets BasicFileAttributes too
        try (var s = Files.find(Path.of("."), 5,
                (p, attrs) -> attrs.size() > 1_000_000)) {
            s.forEach(System.out::println);
        }
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.