-1

Create a java file object and call its deleteOnExit, then call delete programmatically and the close the JVM or program exits

Will deleteOnExit throw any exception as file was already deleted programatically?

Sagii
  • 178
  • 2
  • 13
  • What do you think? And if the JVM is exiting, does it matter? – Kayaman Nov 19 '21 at 09:01
  • 2
    Avoid `deleteOnExit` as it will cause OutOfMemoryError in long running servers, get into habit of using try-finally block to clean up as in this [answer](https://stackoverflow.com/questions/63017828/deleteonexit-not-deleting-file-despite-closing-of-stream-writing-to-it/63030811#63030811). – DuncG Nov 19 '21 at 14:10

1 Answers1

4

If the files is deleted already, nothing will happen. However, it might get deleted if you re-create it.

Even File#delete doesn't throw an exception if the file does not exist, cannot be deleted. It would just return false in that case.

However, File#deleteOnExit saves a reference to the File that is kept even if you delete the file manually. Doing this multiple times will result in more and more references to deleted File objects hanging around in the heap, resulting in a memory leak and potentially in an OutOfMemoryError (see here) since you also cannot abort File#deleteOnExit:

Once deletion has been requested, it is not possible to cancel the request. This method should therefore be used with care.

tquadrat
  • 3,033
  • 1
  • 16
  • 29
dan1st
  • 12,568
  • 8
  • 34
  • 67