gpt4 book ai didi

Windows 上的 Java WatchService 在复制内容之前通知文件夹创建

转载 作者:行者123 更新时间:2023-12-01 05:03:43 25 4
gpt4 key购买 nike

我尝试使用 Java 7 和 WatchService 来监视文件夹何时添加到文件夹(通过从不同位置复制),然后我想对新创建的文件夹中的文件进行操作。

在 OSX 上,它按我的预期工作,在复制文件夹及其内容之前,我不会收到新文件夹创建的通知。但在 Windows 上,我在复制文件夹内容之前收到了文件夹创建的关键事件,因此当我尝试处理文件夹中的文件时,文件夹中的文件不存在,通常只有第一个文件存在。

我当前的解决方法是在收到文件夹通知后,我会睡 10 秒钟以等待复制其中的文件,但这并不是很令人满意,因为文件夹的大小可能相差很大,所以我睡的时间不够长或者大多数时候太长。

为什么 OSX 和 Windows 之间存在差异,以及如何在 Windows 上解决我的问题?

最佳答案

WatchService 的目的是在一定程度上依赖于平台。来自 Java 7 API documentation :

    The implementation that observes events from the file system is 
intended to map directly on to the native file event notification
facility where available, or to use a primitive mechanism, such as
polling, when a native facility is not available. Consequently, many
of the details on how events are detected, their timeliness, and
whether their ordering is preserved are highly implementation specific.

考虑以下两种情况。

  • 单个复制操作花费的时间比 sleep 时间更长。
  • 对同一文件夹进行多次复制操作。

如果您响应文件夹内容的创建而不是文件夹本身,则您将涵盖这两种情况。您还可以消除 sleep 中固有的竞争条件。

关于Windows 上的 Java WatchService 在复制内容之前通知文件夹创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13012487/

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