Prevents forgetting to delete temporary files and quitting without deleting files at the time of abnormal termination.
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_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