what is the difference between delete() and deleteOnExit() methods in java.io.File class in Java?
4 Answers
delete() will delete the file at once, while deleteOnExit() will not delete the file, when you call it. Instead the file is deleted, when the program ends or more precise the virtual machine terminates.
In case the virtual machines terminates not regulary, deleteOnExit() has no effect.

- 1,685
- 1
- 17
- 25
-
I don't know if this is improved behaviour or not, but On Windows 11 and with OpenJDK 19 - Eclipse Temurin JDK with Hotspot 19+36(x64) the file will even be deleted if the user forcefully closes the application or JavaVM with the tasks manager (I just tested this today). So maybe they have improved this in later versions? – Remzi Cavdar Oct 31 '22 at 00:27
File.delete() method deletes the file or throws an exception if the deletion fails. For example, if the file does not exist a NoSuchFileException is thrown. To delete a directory, the directory must be empty. This method returns true if the file is successfully deleted, else false (may be due to read/write permissions). This method is used when you want to delete a known file/directly.
File.deleteOnExit() This method deletes the file or directory defined by the abstract path name when the virtual machine terminates. Files or directories are deleted in the reverse order as they are registered. The method does not return any value. This is useful when generating temporary files during program execution.

- 223
- 5
- 11
Delete() returns boolean Deletes the file or directory denoted by this abstract pathname.
deleteOnExit() returns void Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

- 10,108
- 9
- 71
- 116
File.deleteOnExit() documentation is miss leading. I'm using it on a project and in practice it works by deleting the file when the garbage collector runs (if there is no object referencing the file).

- 47
- 4
-
1deleteOnExit() has nothing to do with the garbage collector. You may see it from its code even: your file is just added to some list of the files that should be deleted when virtual machine terminates. – Boris Aug 19 '20 at 08:29
-
@Boris Actually, deleteOnExit() has nothing to do with the garbage collector but I observed a behavior similar to what ticot55 described too, the file gets deleted earlier than when the virtual machine terminates or we don't understand what it really implies. I'm calling this method in a thread. – gouessej Nov 16 '22 at 13:12