← 中文资源

简体中文版本

DELETE_ON_CLOSE 自动清理临时文件

打开文件通道时带上 DELETE_ON_CLOSE:通道关闭文件即被删除,异常路径也不漏;比 finally 里补 deleteIfExists 更可靠,临时产物自动消失。

阅读英文原文

实现说明

DELETE_ON_CLOSE 自动清理临时文件的核心是类 ScratchArtifact。 try 头部在每条退出路径上关闭声明的资源;finally 块在此之外做额外清理。

使用要点

  • 直接运行文件,输出会带上标签,比如 while open:、after close:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「DELETE_ON_CLOSE 自动清理临时文件」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 while open:、after close: 这类标签。

核心语句

channel.write(ByteBuffer.wrap("scratch payload".getBytes(StandardCharsets.UTF_8)));
Path scratch = Files.createTempFile("report-", ".tmp");

代码示例

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class ScratchArtifact {

    public static void main(String[] args) throws IOException {
        Path scratch = Files.createTempFile("report-", ".tmp");

        // DELETE_ON_CLOSE:通道关闭时文件随之删除,不依赖 finally 里的清理
        try (FileChannel channel = FileChannel.open(scratch,
                StandardOpenOption.WRITE, StandardOpenOption.DELETE_ON_CLOSE)) {
            channel.write(ByteBuffer.wrap("scratch payload".getBytes(StandardCharsets.UTF_8)));
            System.out.println("while open: " + Files.exists(scratch));
        }

        // 退出 try 块即触发 remove:无论正常返回还是异常退出都不留垃圾
        System.out.println("after close: " + Files.exists(scratch));
    }
}