Does File.deleteOnExit() guarantee that the file is deleted even if the JVM is killed prematurely?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
As Tim Bender notes,
File.deleteOnExit()
does not guarantee that the file actually gets deleted.On Unixish systems (such as Linux or OSX), however, it's possible to delete the temporary file before writing to it (but after opening it). As long as you keep an open descriptor to the file, you can keep reading from and writing to it just fine, even though the file no longer exists in the directory tree, and the OS will automatically reclaim the space used by the file when your program exits (or closes the last descriptor to the file).
This won't work on Windows, which has different file system semantics and doesn't allow open files to be deleted. However, in portable code, you can simply try deleting the file after opening it and, if that doesn't succeed, fall back on
deleteOnExit()
:Note that, apparently,
File.deleteOnExit()
is not very reliable on Windows. Thus, whenever possible, you should still try to manually close and delete your temp files when you're done with them. For more details, see this answer I wrote to another question.No. check the file at next start-up if possible.