Search code examples
javaioapache-commonsapache-commons-io

Problems deleting a file with Java (apache commons io)


I am calling a C++ Method via JNI which creates two files. A text log file and a pdf file in a given 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 that. When I execute I get an IOException:

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

I check the writable state of the file before fireing the delete method with the File.canWrite() method. It returns true for both the file and the parent dir.

Do you have an idea why I have problems deleting the file? As far as I know the C++ method which is creating the files is closing or unlocking them after the method finishes. Anyway, I don't have access to the source code of the C++ code so I can't check if that is really the case or modify the code.


Solution

  • It is almost certainly locked by another process. If it is another process locking at the OS level (say you had the file open it a text editor) then you won't have much luck. Even windows explorer can fail to delete a file if something else is locking it. However have a look at java.nio.channels.FileLock for the relevant API calls.