Another solution when it comes to deleting a temporary file relies on StandardOpenOption.DELETE_ON_CLOSE (this deletes the file when the stream is closed). For example, the following piece of code creates a temporary file via the createTempFile() method and opens a buffered writer stream for it with DELETE_ON_CLOSE explicitly specified:
Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
String customFilePrefix = "log_";
String customFileSuffix = ".txt";
Path tmpFile = null;
try {
tmpFile = Files.createTempFile(
customBaseDir, customFilePrefix, customFileSuffix);
} catch (IOException e) {
...
}
try (BufferedWriter bw = Files.newBufferedWriter(tmpFile,
StandardCharsets.UTF_8, StandardOpenOption.DELETE_ON_CLOSE)) {
//simulate some operations with temp file until delete it
Thread.sleep(10000);
} catch (IOException | InterruptedException e) {
...
}
This solution can be adopted for any file. It is not specific to temporary resources.