简体   繁体   中英

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.

Thanks, Marco

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.

最有可能的是,另一个进程是保持file.log打开,这将阻止它被删除。

I'm running Eclipse 4.x and jre 1.7, webapp deployed to tomcat7.

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

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

It doesn't work from within the webapp. But... it works in a standalone java app, run from the same IDE.

Perhaps Tomcat is locking the folder, since I did read earlier(but only by instantiating File() class). I'm not explicitly using streams.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM