Infrastructure at your Service

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

5 Comments

  • frans daniel says:

    Long path error!
    “Long path tool” is very helpful for this problem. You can solve this problem like copy, delete, long path files by using this tool. I used to have similar problems too, but after using “long path tool” everything was solved.

  • Peter Adamson says:

    I suggest you try Long path tool is the very good program for easily delete, copy & rename long path files, error, unlock solution.
    Try it and solve your problem.
    I used long path tool and I solve my error, unlock problem solution.

  • Eyüp Can says:

    System.gc(); helped me, thank you!

  • Steven Crag says:

    I highly recommend Long Path Tool it automatically deletes the folder you selected, including all its files and subfolders, regardless of their path length (even if they are in a network folder).

  • Ana Gray says:

    I had this problem and Long Path Tool was very helpful

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Middleware Team
Middleware Team