Does File.deleteOnExit() guarantee that the file is deleted even if the JVM is killed prematurely?
Deletion will be attempted only for normal termination of the virtual machine, as defined by the Java Language Specification
No. check the file at next start-up if possible.
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()
:
File tempFile = File.createTempFile("tempfile", ".tmp");
RandomAccessFile fh = new RandomAccessFile (tempFile, "rw");
// try to delete the file now, fall back to deletion on exit
if ( !tempFile.delete() ) tempFile.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.
Deletion will be attempted only for normal termination of the virtual machine, as defined by the Java Language Specification
No. check the file at next start-up if possible.
© 2022 - 2024 — McMap. All rights reserved.