Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.delete() returns false

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?

like image 735
Shailesh Tainwala Avatar asked Sep 10 '26 10:09

Shailesh Tainwala


2 Answers

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?

like image 186
Jon Skeet Avatar answered Sep 13 '26 01:09

Jon Skeet


In your case the logger is writing it in the file - The file is locked by another process.


Updates:

The problem is that the log4js' appender has a write lock on your file. So while the appender is not closed, you cannot delete the file. A solution would be you generated smaller files, or to set the append flag to false, so when you restart your server, the old log file is deleted automatically.

Try using

org.apache.log4j.LogManager.shutdown();

Shutting down make sure that all the processes that are using log files are terminated and this way resolved the issue.

Make sure to call the close() method of our own Appender implementation (which is a subclass of AppenderSkeleton), so that it properly closes the appenders from getAllAppenders().

like image 33
Dead Programmer Avatar answered Sep 13 '26 00:09

Dead Programmer