Windows上的Java WatchService在复制内容之前通知文件夹创建 [英] Java WatchService on Windows informing of folder creation before contents have been copied

查看:154
本文介绍了Windows上的Java WatchService在复制内容之前通知文件夹创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Java 7和WatchService监视何时将文件夹添加到文件夹(通过从其他位置复制),然后要对新创建的文件夹中的文件进行操作.

I'm trying to use Java 7 and WatchService to monitor when folders are added to a folder (by being copied from a different location), then I want to act on the files within the newly created folder.

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

On OSX it works as I expect, I don't receive notification of new folder creation until the folder and its contents have been copied over. But on Windows I receive the key event on the folder creation before the contents of the folder have been copied so when I try to process the files within the folder there are not there, usually just the first file is there.

我当前的解决方法是在收到文件夹通知后,我睡眠10秒钟以等待复制其中的文件,但这不是很令人满意,因为文件夹的大小可能相差很大,因此Im睡眠时间不足或大部分时间太长.

My current workaround is after receiving the folder notification I sleep for 10 seconds to wait for the files within to be copied over but this is not very satisfactory because the size of folders can vary considerably so Im going to be sleeping not long enough or too long most of the time.

为什么OSX和Windows有区别,如何在Windows上解决我的问题?

Why the difference between OSX and Windows, and how can I solve my problem on Windows ?

推荐答案

WatchService旨在与平台相关.从 Java 7 API文档:

WatchService is intended to be somewhat platform-dependent. From the 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.

请考虑以下两种情况.

  • 单次复制操作所需的时间比睡眠时间长.
  • 将多个复制操作复制到同一文件夹中.

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

If you respond to the creation of the folder contents rather than the folder itself, you cover both these cases. You can also eliminate the race condition inherent in the sleep.

这篇关于Windows上的Java WatchService在复制内容之前通知文件夹创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆