I think I'm misunderstanding how the FileChannel's locking features work.
I want to have an exclusive write lock on a file, but allow reads from any process.
On a Windows 7 machine running Java 7, I can get FileChannel's lock to work, but it prevents both reads and writes from other processes.
How can I achieve a file lock that disallows writes but allows reads by other processes?
FileChannel.lock()
deals with file regions, not with the file itself.I guess you are looking for a bit different feature - to open a file for writing while allowing other processes to open it for reading but not for writing.
This can be achieved by Java 7 FileChannel.open API with non-standard open option:
import static java.nio.file.StandardOpenOption.*;
import static com.sun.nio.file.ExtendedOpenOption.*;
...
Path path = FileSystems.getDefault().getPath("noshared.tmp");
FileChannel fc = FileChannel.open(path, CREATE, WRITE, NOSHARE_WRITE);
Note ExtendedOpenOption.NOSHARE_WRITE
which is a non-standard option existing in Oracle JDK.
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