Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making sure file gets deleted on JVM exit

Tags:

java

file

java-io

Does File.deleteOnExit() guarantee that the file is deleted even if the JVM is killed prematurely?

like image 904
Hamza Yerlikaya Avatar asked Sep 15 '09 01:09

Hamza Yerlikaya


2 Answers

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.

like image 118
Ilmari Karonen Avatar answered Sep 18 '22 20:09

Ilmari Karonen


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.

like image 26
Tim Bender Avatar answered Sep 18 '22 20:09

Tim Bender