2

In my app I'm writing a file to store some execution info and once the execution is done I want to delete the temp file. The issue is even after file close or flush by streams I cannot delete the file. I tried

Thread.sleep(1000);
file.delete();

and that didn't delete the file either. I then created a while loop

while(!file.delete())
   Thread.sleep(1000);

and it was looping forever. I then added

System.gc();
file.delete();

and it worked!!!

I have verified that I have gracefully closed or flushed the file. I want to know why my code worked with System.gc()?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Vig
  • 1,532
  • 1
  • 11
  • 28
  • 6
    Make sure that you've closed all open file streams before you attempt to delete the file. – mre Feb 22 '12 at 16:26
  • It's still true. It is a Windows related bug JDK-4715154. Probably that's why there is special `scala.compat.Platform.collectGarbage()` entry in the Scala run-time library. – Epicurist Aug 18 '14 at 11:46

2 Answers2

3

That seems to indicate that you did not call close().

Reason: in the begin time of java, the Object.finalize() method was used to clean up on garbage collection, and for I/O it did a close().

Until the file is in use (not closed), the file cannot be deleted on Windows.

Joop Eggen
  • 102,262
  • 7
  • 78
  • 129
0

What you want to use is File.createTempFile() and call deleteOnExit() on the resulting file. It will manage cleaning up the temp file at the end of execution for you. You shouldn't be doing this manually, let the system do this for you, that is why they included this in the standard library.

Also you should always call .close() to make sure that all the data is flushed to the file and the handle can be cleaned up correctly.

  • 1
    File.createTempFile() does not do any cleanup work. It just creates a file with a unique name in a temp directory. The application should still delete the file when it is done with it. – Michael Krussel Feb 22 '12 at 17:12