So i used the following to create a lock on a file so that I can edit it exclusively:
File file = new File(filename);
channel = new RandomAccessFile(file, "rw").getChannel();
lock = channel.tryLock();
Now I have a 2nd thread want to access the same file - just to read, not edit. How do i do that? Right now the 2nd thread will throw an io exception and inform me the file is locked.
Is this doable? Any suggestions? Thanks
Verify that the file has not been corrupted and that the file extension matches the format of the file. A reason why would you want to unlock the file is one good way to start the question. The operating system won't permit it. There is nothing you can do about it 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.
In Java, a file lock can be obtained using FileChannel , which provides two methods — lock() and tryLock() — for this purpose. The lock() method acquires an exclusive lock on entire file, whereas the lock(long position, long size, boolean shared) method can be used to acquire a lock on the given region of a ile.
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.
You could try asking for a shared lock using the three argument version of tryLock.
Here is the appropriate javadoc: http://download.oracle.com/javase/1.4.2/docs/api/java/nio/channels/FileChannel.html#tryLock%28long,%20long,%20boolean%29
Basically instead of doing
lock=channel.tryLock()
you would do lock = channel.trylock(0, Long.MAX_VALUE, true)
As an aside, you should be careful with file locking in java. While you can guarantee the locks behave as expected within the JVM you can't necessarily be sure that they will behave as expected accross multiple processes.
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