如何从操作系统上所有其他进程的 Java 应用程序中锁定文件?

How can I lock a file from within a Java application for all other processes on a operating system?

我有一个文件需要多次阅读。我必须按顺序将 InputStream 打开到同一个文件。现在我想知道只要 Java 应用程序的特定部分是 运行,是否可以为整个 os 锁定该文件

我想防止3发生:

  1. 正在从 myApp.java 读取文件 example.txt
  2. 停止读取文件example.txt
  3. 其他进程写入文件(即echo "foo" >> example.txt
  4. 正在从 myApp.java 读取文件 example.txt

据我了解java.nio.FileChannel lock 只会锁定其他 JVM 应用程序对文件的访问。

文件系统是 OS/implementation 特定的 WRT "locking",我的猜测是要可靠地做到这一点,您必须通过文件权限来做到这一点。

您没有提供有关 OS/filesystem 类型的任何详细信息,因此没有具体的答案。

如果有办法 "lock" 文件系统上的某些文件,我敢打赌它不会是可移植的。

我有一个防止其他进程可以访问此文件的想法是重命名它,直到您的应用程序完成。

1. Load the file and rename it. For example, example.txt to example.txt.tmp
2. Reading file example.txt.tmp from myApp.java
.....
6. Rename your file name back to the original one.

JavaAPI为java.nio.channels.FileLock。你说:

As far as I understand java.nio.FileChannel lock does only lock access to a file for other JVM applications.

这种理解是不正确的。来自 FileLock 的文档:

Platform dependencies

This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written [emphasis added].

Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified. The native file-locking facilities of some systems are merely advisory, meaning that programs must cooperatively observe a known locking protocol in order to guarantee data integrity. On other systems native file locks are mandatory, meaning that if one program locks a region of a file then other programs are actually prevented from accessing that region in a way that would violate the lock. On yet other systems, whether native file locks are advisory or mandatory is configurable on a per-file basis. To ensure consistent and correct behavior across platforms, it is strongly recommended that the locks provided by this API be used as if they were advisory locks.

[...]

但是,如您所见,锁定的确切性质是特定于平台的。