gpt4 book ai didi

java - 获取文件的锁

转载 作者:行者123 更新时间:2023-11-30 11:58:12 25 4
gpt4 key购买 nike

我想在对特定文件启动 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com