Skip to content

Java: Cannot delete file?

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();
}

Let’s work together

Ready to operate at
the next level?

Tell us about your challenge. We’ll bring the depth, the expertise, and the Swiss precision.

Middleware Team

Middleware Team

Posts published under the Middleware Team account are collective contributions by the dbi services middleware and enterprise content management consultants. The practice covers ECM platforms such as OpenText Documentum, Alfresco, and M-Files, as well as application servers and integration technologies including WebLogic, JBoss, Tomcat, and the Elastic Stack, from architecture and deployment to operations under service level agreements.View Author posts

322 posts since February 2013

Most read in Application Server

The Application Server posts our readers open most: the all-time favourites, and what is trending right now.

Leave a Comment

Your email address will not be published. Required fields are marked *