File.delete() returns false

Shailesh Tainwala picture Shailesh Tainwala · Mar 23, 2011 · Viewed 8.6k times · Source

I have created a file from my java programming, and am logging some data use Apache Commons Logging API, specifically the Log4j implementation.

After the logging has been done, I am setting the reference to the Log class as null. When I now try to delete the file to which I have been logging, File.delete() returns false.

Deleting the file from windows explorer during debugging (at the point just before File.delete() is called), I get the notification "cannot delete: being used by another program".

There are no open dependencies on the file from my code (all streams are closed). The only object that could be accessing the file is the Log object, which I have set to null before calling File.delete()

Is there anyway I can see what specific object is holding a reference to the file resource? Is there any other way to force the Log object to release resource, other than setting it to null? Can I force a delete on the file?

Answer

Jon Skeet picture Jon Skeet · Mar 23, 2011

Just setting the variable to null doesn't force the object to be garbage collected. Also, there's a chance that it's registered in some sort of static map - you'd have to check the implementation to be sure. (I think some versions use weak references, but others don't.)

Is there any reason you have to delete the file right then? You might want to try File.deleteOnExit(), which may have a better chance of deleting the file - although it depends on exactly what the timing is like. (Also, beware of a possible memory leak if you call deleteOnExit repeatedly.)

Could you just delete the file after the application has finished, or possibly on the next start-up?

Alternatively, can you use a log implementation which rolls the files over - try to force a rollover, and then delete the old file?