java - 获取文件的锁

标签 java

我想在对特定文件启动 threo read 时获取文件上的锁,这样其他应用程序就无法读取已经锁定的文件,并希望在线程终止时释放锁定文件。

最佳答案

您可以获得 FileLock通过FileChannel .获取 FileChannel:

In this release a file channel can be obtained from an existing FileInputStream, FileOutputStream, or RandomAccessFile object by invoking that object's getChannel method, which returns a file channel that is connected to the same underlying file.

但是,Java 无法控制操作系统提供的文件锁定类型,因此 API 的建议是像使用咨询文件锁一样使用锁。

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.

关于java - 获取文件的锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3315553/

相关文章:

java - 过去 24 小时的总计时间

java - 我应该为 Android 中的日期使用什么类?

Java服务器-多客户端TCP连接I/O

java - 如何管理嵌入式 OSGi 应用程序中的 bundle /依赖项?

java - 用于确定 Java 中的类声明的强大正则表达式

java - 使用 Java 泛型的责任链处理程序

java - 如何添加线程或池以避免 ConnectException : Connection refused?

java - Person 不能转换为 HashMap<String, Person>

java - Java中的除法以获得下一个更高的值

java - 通过 ExecutorService 执行 Thread 时 Thread.join() 不起作用