After years of coding with the old File API, I'm finally ready to hop onto the whole Path/Paths train. For the most part, this has gone smoothly, however, I'm stumped on this particular aspect: temporary files.
The documentation on java.nio.Files#createTempFile says:
As with the
File.createTempFilemethods, this method is only part of a temporary-file facility. Where used as a work files, the resulting file may be opened using theDELETE_ON_CLOSEoption so that the file is deleted when the appropriate close method is invoked. Alternatively, a shutdown-hook, or theFile.deleteOnExit()mechanism may be used to delete the file automatically.
I don't see where the DELETE_ON_CLOSE option is supposed to be specified. Using a shutdown hook is incredibly inconvenient (unless I'm thinking of it wrong). In an effort to avoid using both Path objects and File objects, I am looking for a solution similar to the File.deleteOnExit() for the Path object, but obviously one that doesn't require using Path.toFile().[...].toPath() sort of calling pattern.
What is the correct way to implement "self-destructing" temporary files using the java.nio.Files API?
You set that option when you write, for example:
Path myTempFile = Files.createTempFile(...);
Files.write(myTempFile, ..., StandardOpenOption.DELETE_ON_CLOSE);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With