Java I/O:确保文件在任何读/写操作之前没有被另一个进程锁定

发布于 2024-12-25 19:09:58 字数 499 浏览 1 评论 0原文

我在基于 Java 7 WatchService API 跟踪目录中文件内容的应用程序中经常遇到问题。当底层文件系统在文件上触发修改事件时,我想立即计算其 SHA-256。

但经常会发生另一个进程打开该文件(即Word),从而保留独占锁并阻止我的应用程序进行任何读/写操作。如果针对打开的文件创建任何 Stream/Channel,则会抛出 FileNotFoundException 或 nio API 的 FileSystemException,并显示如下消息:

该进程无法访问该文件,因为该文件正在被另一个进程使用

当文件实际上不存在于 fs 上时,我无法提供一种解决方案来检测此类情况,而无需屏蔽“真正的”FileNotFoundException。

我想出了通过 File.exists 检查存在性的想法,然后如果在打开流时抛出 FileNotFoundException,我将能够推断该文件已被锁定。我愿意接受任何对此的意见!

谢谢!

I'm encountering a recurrent issue in an application that tracks content of files within a directory, based on the Java 7 WatchService API. When the underlying file system fires a modification event on a file, I want to compute its SHA-256 right away.

But it often occurs that another process has the file opened (i.e. Word), thus detaining an exclusive lock and preventing my app from any read/write operation. If any Stream/Channel is created against the opened file, a FileNotFoundException or a FileSystemException for nio API's is thrown with a message like :

The process cannot access the file because it is being used by another process

I wasn't able to come with a solution that would detect such cases without masking a "real" FileNotFoundException when the file does not actually exists on the fs.

I've come up with the idea to check existence via File.exists and then if a FileNotFoundException is thrown when I open a stream I would be able to infer that the file is locked. I am open to any input on this!

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瞎闹 2025-01-01 19:09:58

您是否尝试过自己锁定文件?我假设您只能在未锁定且存在的情况下获取锁。

http://docs .oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#tryLock%28%29

Have you tried locking the file yourself? I would assume you can only acquire a lock if its not locked and exists.

http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#tryLock%28%29

属性 2025-01-01 19:09:58

跨进程共享文档是很棘手的,尤其是在不使用专用文件系统(例如 GFS )时。我不认为 Java 锁定 API 对您有多大帮助,我认为您的尝试想法是正确的/fail策略...使用java 7,您可以使用WatchService来监视文件更改,然后按照您的业务需求进行操作...您使用什么样的系统? Windows 永远保留文件句柄...

HTH
杰罗姆

sharing documents accross processes is tricky especially when not using dedicated file systems (like GFS can be ).. I don't think that Java locking API may help you much, I think that you are on the right way with your idea of the try/fail strategy ... Using java 7 you could use a WatchService to monitor file changes and then acting as stated by your business requirements... What kind of system do you use ? Windows keeps handles on files during eternity...

HTH
Jerome

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文