Files.walk MaxDepth Controls Tree Levels

Pass maxDepth to Files.walk to stop at 0, 1, or N directory levels, keeping deep subdirectories unread while closing the stream via try-with-resources.

JavaCli Tooling

Code

snippet
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;

public class BoundedTreeWalk {

    public static void main(String[] args) throws IOException {
        Path root = Files.createTempDirectory("walk-depth-");
        Path level1 = Files.createDirectory(root.resolve("src"));
        Path level2 = Files.createDirectory(level1.resolve("api"));
        Files.writeString(root.resolve("README.md"), "root");
        Files.writeString(level1.resolve("Main.java"), "class Main {}");
        Files.writeString(level2.resolve("Deep.java"), "class Deep {}");

        for (int depth : new int[] {0, 1, 2}) {
            // maxDepth=0 yields only root; maxDepth=1 stops at immediate children
            try (Stream<Path> stream = Files.walk(root, depth)) {
                List<String> rel = stream
                        .map(p -> root.relativize(p).toString().replace('\\', '/'))
                        .map(s -> s.isEmpty() ? "." : s)
                        .sorted()
                        .toList();
                System.out.println("maxDepth=" + depth + " -> " + rel);
            }
        }

        try (Stream<Path> cleanup = Files.walk(root)) {
            cleanup.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
        }
    }
}

Implementation flow — Files.walk MaxDepth Controls Tree Levels

The moving parts are the classes BoundedTreeWalk, Main and Deep.

for (int depth : new int[] {0, 1, 2}) executes item-by-item iteration over the collection elements. Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

What to watch for

  • Standard toolchain alone suffices — zero dependency lookup takes place.

Using it

The file’s steps show up in the output as maxDepth=.

Key statements

.map(p -> root.relativize(p).toString().replace('\\', '/'))
.map(s -> s.isEmpty() ? "." : s)
.sorted()
.toList();

Interactive Tools for This Topic

FAQ

What does Files.walk MaxDepth Controls Tree Levels print when run?
Running the file directly is enough — expect labeled output lines such as `maxDepth=`.