Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a file is already open before trying to delete it [duplicate]

Tags:

java

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
like image 208
divz Avatar asked Dec 26 '11 09:12

divz


People also ask

How do you check file is opened or not in Java?

Core Java bootcamp program with Hands on practice io. File. canRead() is used to check if a file or directory is readable in Java. This method returns true if the file specified by the abstract path name can be read by an application and false otherwise.

How do you check if a file is opened by another process in Python?

Any file is required to open before reading or write. The open() function is used in Python to open a file. Using the open() function is one way to check a particular file is opened or closed. If the open() function opens a previously opened file, then an IOError will be generated.

How do you check if a file is being written Python?

Simply open the file in Python and move the read/write pointer to the end of the file using the seek() method, then retrieve its position using the tell() method, this position is equal to the size of the file in bytes.

How do you check if the file is being used by another process in Java?

The File class has two methods called canRead( ) and canWrite( ). I beleive that if you use either of these when they point to your File in question then they will tell you if there is any process maintaining a lock on it. File processCheck = new File( c:\temp\TheFile. txt );


1 Answers

I don't think this is going to work for a few reasons.

  1. There are no standard Java mechanisms for testing if you already have a file open.

  2. Even if there were such a mechanism, it would be difficult to find the file's handle so that you could close it.

  3. 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.

  4. 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.

like image 63
Stephen C Avatar answered Sep 30 '22 06:09

Stephen C