本文介绍了使用java FileChannel FileLock来防止文件写入但允许读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我误解了FileChannel的锁定功能是如何工作的。

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.

在运行Java 7的Windows 7计算机上,我可以使FileChannel的锁定工作,但它会阻止来自其他进程的读取和写入。

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()处理文件区域,而不是文件本身。

  • 锁定可以要么共享(许多读者,没有作家)或独家(一个作家,没有读者)。

    • 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.

      这可以实现作者:Java 7 带有非标准开放选项的API:

      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);
      

      注意 ExtendedOpenOption.NOSHARE_WRITE 这是非Oracle JDK中存在标准选项。

      Note ExtendedOpenOption.NOSHARE_WRITE which is a non-standard option existing in Oracle JDK.

      这篇关于使用java FileChannel FileLock来防止文件写入但允许读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 05:43