I am doing the exception handling in a java program. I don't want to copy, transfer or delete a file if it is open. The trouble is: I can't find in the java API's any method that would check if a file is open. Can anyone help ?
You might want to do a search - I remember that there was a similar discussion recently...
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Are you concerned that the file might be held open by some other code runing in the same JVM, or by some other process outside the JVM? If it's the latter, you may be able to decect this using the tryLock() method in java.nio.FileChannel. If this returns null, that means another process has a lock on the file for some reason. If you're more interested in detecting if the file is held open by this JVM, I'm not sure if this will work. But the API seems to imply an exception will be thrown if the lock is already held elsewhere. So I suppose you could catch it.
Otherwise, I don't know of an API that detects this for you. I would recommend that for code in the same JVM, you should probably try to make sure that anytime you open a file (create a FileOutputStream or whatever), you close() the file inside a finally block. In that case, you'll be sure the file got closed, period, and you won't need to query another method to find out if it's open. There may be some cases where this is not possible to guarantee, but I think they're rare.
1) It's platform-specific. It won't work on Linux, as we're allowed to delete and rename files that other applications are using.
2) It's not atomic. Even if that tells you the file is "not open", so what? By the time your Java app goes to access it, another app might have opened it. So you have to be able to deal with the case of trying (and failing) to access an already opened file anyway. It's like testing if a server is up before trying to connect to it--mostly pointless.