Problems deleting a file using Java (apache commons io)

I call the C ++ method via JNI, which creates two files. The text log file and the PDF file in this directory. I want to delete these files (if they exist) before executing the JNI method.

I am using Apache commons.io (FileUtils.forceDelete (file file)) for this. When I execute, I get an IOException:

java.io.IOException: Unable to delete file: D:\Folder\file.log 

I check the rewritable state of the file before running the delete method with the File.canWrite () method. It returns true for both the file and the parent directory.

Do you have an idea why I have problems deleting a file? As far as I know, a C ++ method that creates files closes or unlocks them after the method finishes. In any case, I do not have access to the source code of the C ++ code, so I can not check whether this is true, or change the code.

Thanks Marco

+7
source share
3 answers

It is almost certainly blocked by another process. If this is another OS-level locking process (let's say you opened the file with a text editor), you're out of luck. Even Windows Explorer may not delete the file if something else blocks it. However, look at java.nio.channels.FileLock for the corresponding API calls.

+7
source

Most likely, another process supports file.log open, which will prevent it from being deleted.

+1
source

I am running Eclipse 4.x and jre 1.7, the webapp is deployed to tomcat7.

I have the same problem trying to delete files from my spring controller.

 File f = new File("/home/me/my/file/liveshere/smallfile.txt"); f.delete(); 

This does not work from webapp. But ... it works in a standalone Java application, runs from the same IDE.

Tomcat may be locking the folder, as I read earlier (but only by creating an instance of the File () class). I do not use streams explicitly.

I also tried using the commons.io library for FileUtils.forceDelete (f), but still had no joy.

0
source

All Articles