My Java program wants to read a file which can be locked by another program writing into it. I need to check if the file is locked and if so wait until it is free. How do I achieve this?
The Java program is running on a Windows 2000 server.
If the file is exclusively locked (by MS Word for example), there will be exception: java. io. FileNotFoundException: <fileName> (The process cannot access the file because it is being used by another process) . This way you do not need to open/close streams just for the check.
Select the file you want to unlock, or open it in the editor. Select VCS | Subversion | Unlock from the main menu, or Subversion | Unlock from the context menu of the selection.
You can run from Java program the lsof Unix utility that tells you which process is using a file, then analyse its output. To run a program from Java code, use, for example, Runtime , Process , ProcessBuilder classes.
A token representing a lock on a region of a file. A file-lock object is created each time a lock is acquired on a file via one of the lock or tryLock methods of the FileChannel class, or the lock or tryLock methods of the AsynchronousFileChannel class. A file-lock object is initially valid.
Should work in Windows:
File file = new File("file.txt"); boolean fileIsNotLocked = file.renameTo(file);
Under Windows with Sun's JVM, the FileLocks should work properly, although the JavaDocs leave the reliability rather vague (system dependent).
Nevertheless, if you only have to recognize in your Java program, that some other program is locking the file, you don't have to struggle with FileLocks, but can simply try to write to the file, which will fail if it is locked. You better try this on your actual system, but I see the following behaviour:
File f = new File("some-locked-file.txt"); System.out.println(f.canWrite()); // -> true new FileOutputStream(f); // -> throws a FileNotFoundException
This is rather odd, but if you don't count platform independence too high and your system shows the same behaviour, you can put this together in a utility function.
With current Java versions, there is unfortunately no way to be informed about file state changes, so if you need to wait until the file can be written, you have to try every now and then to check if the other process has released its lock. I'm not sure, but with Java 7, it might be possible to use the new WatchService to be informed about such changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With