DELETE_ON_CLOSE Removes Temp Files

Open a temp file channel with StandardOpenOption.DELETE_ON_CLOSE so the scratch file disappears when the channel closes, even on failure paths.

JavaCli Tooling

Code

snippet
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));
    }
}

How it works

The working surface is the class ScratchArtifact — everything else is wiring.

try-with-resources closes each declared resource automatically on every exit path.

Points of care

  • The only prerequisite is the language toolchain itself.

Applying it

The demo output is labeled (while open:, after close:), letting each printed line point back to the operation that emitted it.

Statements that matter

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

Interactive Tools for This Topic

FAQ

What does DELETE_ON_CLOSE Removes Temp Files print when run?
Run it as a complete program — the output lines carry labels such as `while open:`, `after close:`.