← 中文资源

简体中文版本

临时目录作为工作现场

Files.createTempDirectory 生成带随机后缀的临时目录,并发运行互不冲突;工作文件集中写入,结束时按名字倒序递归删除整个现场。

阅读英文原文

实现说明

临时目录作为工作现场可以归结为类 ScratchWorkspace。 资源声明在 try-with-resources 头部,任何退出路径都会自动关闭,无需 finally 块。失败路径是显式的——守卫条件成立就抛出 RuntimeException。

使用要点

  • 跑完文件,输出里会留下标记——scratch:、written:、removed:。

常见问题

输入不合法时代码会怎么表现?

校验先行——RuntimeException 标记失败,不会先做一半再失败。

运行「临时目录作为工作现场」会打印什么?

运行文件本身,scratch:、written:、removed: 这些前缀各对应一段演示逻辑。

核心语句

throw new RuntimeException(e);

代码示例

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

public class ScratchWorkspace {

    public static void main(String[] args) throws IOException {
        // 前缀 + 随机后缀:并发运行互不冲突,目录落在系统临时区
        Path scratch = Files.createTempDirectory("batch-");
        System.out.println("scratch: " + scratch);

        Path work = scratch.resolve("input.txt");
        Files.writeString(work, "row-1\nrow-2\n");

        // 直接在临时目录里再建子目录与文件,工作现场集中一处
        Path nested = Files.createDirectories(scratch.resolve("out"));
        Files.writeString(nested.resolve("result.txt"), "done");

        System.out.println("written: " + Files.readAllLines(work).size() + " rows");

        // 清理:按名字倒序逐个删除,子内容先于父目录消失
        try (Stream<Path> paths = Files.walk(scratch)) {
            paths.sorted(Comparator.reverseOrder()).forEach(p -> {
                try {
                    Files.deleteIfExists(p);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        System.out.println("removed: " + Files.notExists(scratch));
    }
}