实现说明
Files.walk 通过 maxDepth 限制目录遍历深度的核心是类 BoundedTreeWalk、Main、Deep。
文件的主干是一个循环——for (int depth : new int[] {0, 1, 2})。资源声明在 try-with-resources 头部,任何退出路径都会自动关闭,无需 finally 块。
使用要点
- 工具链本身就够——不发生任何依赖解析。
- 直接运行文件,输出会带上标签,比如
maxDepth=——输出的每一行都能指回产生它的那次调用。
常见问题
运行「Files.walk 通过 maxDepth 限制目录遍历深度」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 maxDepth= 这类标签。
核心语句
.map(p -> root.relativize(p).toString().replace('\\', '/'))
.map(s -> s.isEmpty() ? "." : s)
.sorted()
.toList();
代码示例
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());
}
}
}