[Java 7 or later] Prevent temporary file deletion omissions

Purpose

Prevents forgetting to delete temporary files and quitting without deleting files at the time of abnormal termination.

Implementation example

Delete file using delete statement

Delete temporary file with delete statement


    Path path = null;
    try {
        //Temporary file creation
        path = Files.createTempFile("test", ".tmp");
        OutputStream out = Files.newOutputStream(path);
        String data = "test";
        out.write(data.getBytes());

        //Write to file
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //File deletion at the end of processing
        Files.deleteIfExists(path);
    }

In this implementation, it seems that it may not be deleted when the JVM terminates abnormally.

Delete files using DELETE_ON_CLOSE

DELETE_ON_Delete temporary files using CLOSE


    Path path = null;
    try {
        //Temporary file creation
        path = Files.createTempFile("test", ".temp");
        try (BufferedWriter bw = Files.newBufferedWriter(path, StandardOpenOption.DELETE_ON_CLOSE)) {
            String data = "test";
            //Write to file
            bw.write(data);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

When DELETE_ON_CLOSE of StandardOpenOption is used as an option when opening a file, Files are automatically deleted when the stream is closed. Furthermore, by using the "try-with-resources" syntax, closing and file deletion are automatically executed without implementing the close process, so the implementation is neat and there is no omission of deletion.

Recommended Posts

[Java 7 or later] Prevent temporary file deletion omissions
Java (jdk1.8 or later) file input / output sample program
[Java] Create a temporary file
How to remote debug Java 9 or later
NullPointerException countermeasure example (Optional) for Java 8 or later
Review notes for Java 1.7 and later file copies
java file creation
[Gradle] Generate Javadoc including JavaScript in Java 1.8.0_121 or later