14

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.

Thanks, Marco

ollo
  • 24,797
  • 14
  • 106
  • 155
  • Are you sure that the file is not used by another process? Try to manually rename/delete this file. – ahmet alp balkan May 12 '11 at 12:22
  • According to Apache SVN the method delete() on the File object is called before the exception occurs. Which means the specified file could not be deleted as requested. My guess would be, that a lock is still present on the file. – Osiris76 May 12 '11 at 12:24
  • 1
    Any idea how can I remove the lock? –  May 12 '11 at 12:29
  • Without knowledge of the code producing the files it's very difficult to present a solution. Depending on the modes that have been used creating the files you could leave them alone and the method is replacing the files itself. One other source could be using a IDE to run the application. Sometimes IDE's lock files even though they have nothing to do with it. If possible you could also try to delete the whole directory, but that may produce the same result as deleting the files. – Osiris76 May 12 '11 at 12:52
  • Are you using any reader to access the file? You might want to close the reader or implement the reading process using try-with-resources. – Kersy May 22 '20 at 06:10

2 Answers2

10

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.

CodeBuddy
  • 5,749
  • 1
  • 25
  • 30
Nick Fortescue
  • 43,045
  • 26
  • 106
  • 134
2

Most likely, another process is keeping file.log open, which would prevent it from being deleted.

Tony the Pony
  • 40,327
  • 71
  • 187
  • 281