How can I check if a file is already open before trying to delete it
programmatically?
something like this
if (file is open){
// close it first
}
// delete file
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I don’t think this is going to work for a few reasons.
There are no standard Java mechanisms for testing if you already have a file open.
Even if there were such a mechanism, it would be difficult to find the file’s handle so that you could close it.
Even if you could find the file handle, there is a potential race condition where one thread tests a file and attempts to delete it, and a second thread opens the file handle.
None of this addresses the case where some other process has the file open.
If you’ve got a problem deleting files that your application has opened, then it is most likely that the real problem is that your application is leaking file descriptors. And the best solution to that is to find and fix the leak … or to make sure that all of your file streams etc are closed using “try / finally” or the new Java 7 “try with resource” construct.
On the other hand, if the file is opened by some other process, then you may as well just try to delete the file without testing to see if it is open. If the delete succeeds, it succeeds. Otherwise detect the failure and do whatever you would have done if you detected that the file was open.