实现说明
真正干活的是类 FilesCreateDirectoriesIdempotent,其余都是接线。
try-with-resources 会在每条退出路径上自动关闭声明的资源。
使用要点
- 演示输出是带标签的(
createDirectory failed:、nested is a directory:、root still exists:),每个操作都会留下自己的一行标注。
常见问题
运行「Files 建目录的幂等语义」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 createDirectory failed:、nested is a directory:、root still exists: 标签标明各步骤。
核心语句
paths.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
Path root = Files.createTempDirectory("uploads-");
Path nested = root.resolve("2026/11/19");
代码示例
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
public class FilesCreateDirectoriesIdempotent {
public static void main(String[] args) throws IOException {
Path root = Files.createTempDirectory("uploads-");
Path nested = root.resolve("2026/11/19");
// createDirectory:父目录不存在直接抛 NoSuchFileException
try {
Files.createDirectory(nested);
} catch (IOException e) {
System.out.println("createDirectory failed: " + e.getClass().getSimpleName());
}
// createDirectories:逐级补齐,目录已存在也静默通过(幂等)
Files.createDirectories(nested);
Files.createDirectories(nested);
System.out.println("nested is a directory: " + Files.isDirectory(nested));
// 清理演示目录:逆序删除保证子项先于父项
try (var paths = Files.walk(root)) {
paths.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
}
System.out.println("root still exists: " + Files.exists(root));
}
}