using java FileChannel FileLock to prevent file writes but allow reads

牧云@^-^@ 提交于 2019-12-01 19:24:15

问题


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.



来源:https://stackoverflow.com/questions/22646598/using-java-filechannel-filelock-to-prevent-file-writes-but-allow-reads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!