September 2019
Intermediate to advanced
816 pages
18h 47m
English
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)) ...