Java WatchService on Windows informing of folder creation before contents have been copied

拟墨画扇 提交于 2019-12-12 22:36:56

问题


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.

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.

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.

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


回答1:


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.

Consider the following two cases.

  • A single copy operation that takes longer than the sleep.
  • Multiple copy operations into the same folder.

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.



来源:https://stackoverflow.com/questions/13012487/java-watchservice-on-windows-informing-of-folder-creation-before-contents-have-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!