Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a file is locked in Java

Tags:

java

locking

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.

like image 895
Hellnar Avatar asked Sep 30 '09 19:09

Hellnar


People also ask

How do you check if a file is locked by another process in Java?

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.

How do you unlock a file in Java?

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.

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

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.

What is file locking in Java?

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.


2 Answers

Should work in Windows:

File file = new File("file.txt"); boolean fileIsNotLocked = file.renameTo(file); 
like image 160
Vlad Avatar answered Sep 22 '22 13:09

Vlad


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.

like image 38
jarnbjo Avatar answered Sep 18 '22 13:09

jarnbjo