You may once went into the struggle to delete a file in java?

So do I…

logo

I went so mad when I figured out that my files were still present even after a file.delete() or file.deleteOnExit(). It always returned False.
So what’s the reason for it not to be deleted? In fact it’s logical…

When dealing with files you are probably writing into it. So you open a stream to the file like FileWriter or whatever, and you push and flush data to the file.
When finished you have to close your stream like writer.close() BUT it doesn’t close it as you think. In fact there is still pointers/references to the stream and the file.
Hence when trying to delete the file it refuses to do so because it still have ‘stream opened’ on it…

Thus a solution would be to get rid of these unwanted referencing objects; and that’s easier than you think, just call a garbage collection.
Because these objects have been set as ‘garbageable’ if you call the GC they will be deleted and you will be able to delete the files properly.

To do so just call System.gc();
But be careful, it will trigger a full GC and can potentially alter your performances, usually it is not recommended to call it manually inside your code, but if you have several files to delete in a loop, just put then in a List and delete them all in once at the end of your process.

For example:

System.gc();
for(File f : listToDelete){
	f.delete();
}