using java FileChannel FileLock to prevent file wr

2020-04-07 03:09发布

问题:

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?

回答1:

  • FileChannel.lock() deals with file regions, not with the file itself.
  • The lock can be either shared (many readers, no writers) or exclusive (one writer and no readers).

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.