Making sure file gets deleted on JVM exit
Asked Answered
F

2

6

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

Fireback answered 15/9, 2009 at 1:51 Comment(0)
V
5

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.

Vintager answered 15/9, 2009 at 1:58 Comment(0)
O
7

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.

Ohaus answered 22/5, 2013 at 15:2 Comment(1)
this is brilliantBillyebilobate
V
5

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.

Vintager answered 15/9, 2009 at 1:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.