Check if a file is locked in Java
Should work in Windows:
File file = new File("file.txt");
boolean fileIsNotLocked = file.renameTo(file);
Use a FileLock
in all the Java applications using that file and have them run within the same JVM. Otherwise, this can't be done reliably.
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 multiple processes (which can be a mix of Java and non-Java) might be using the file, use a FileLock
. A key to using file locks successfully is to remember that they are only "advisory". The lock is guaranteed to be visible if you check for it, but it won't stop you from doing things to the file if you forget. All processes that access the file should be designed to use the locking protocol.