实现说明
逻辑集中在类 OutputLayout里。
try-with-resources 会在每条退出路径上自动关闭声明的资源。
使用要点
- 演示输出是带标签的(
created:、re-run ok:、createDirectory threw:),每个操作都会留下自己的一行标注。
常见问题
运行「Files.createDirectories 幂等建目录」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 created:、re-run ok:、createDirectory threw: 标签标明各步骤。
核心语句
paths.sorted(java.util.Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
Files.createDirectory(base.resolve("2026/11/summary"));
Path base = Files.createTempDirectory("report-");
代码示例
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class OutputLayout {
public static void main(String[] args) throws IOException {
Path base = Files.createTempDirectory("report-");
Path nested = base.resolve("2026/11/summary");
// 一次性创建整条缺失的父链
Files.createDirectories(nested);
System.out.println("created: " + Files.isDirectory(nested));
// 再跑一遍也不抛异常:目录已存在不算失败,天然幂等
Files.createDirectories(nested);
System.out.println("re-run ok: " + Files.isDirectory(nested));
// 对照:createDirectory 只建最后一级,目标已存在会抛异常
try {
Files.createDirectory(base.resolve("2026/11/summary"));
} catch (IOException alreadyExists) {
System.out.println("createDirectory threw: " + alreadyExists.getClass().getSimpleName());
}
// 清理演示目录树:先删最深层再往上收
try (var paths = Files.walk(base)) {
paths.sorted(java.util.Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
}
}
}