简体   繁体   中英

Using a Java WatchService to monitor folders within folders

I'm trying out WatchService with Java 7, to monitor a folder. I want it to monitor any files or folders being added to the path registered with the WatchService.

If I add a folder to the registered path it detects it correctly as ENTRY_CREATE and returns the name of the folder in watchEvent.context(). But if I add a folder to that folder than again it is detected but watchEvent.context() returns the same folder and ENTRY_MODIFY, because that folder has been modified by adding another folder.

So I understand this but don't know if I should be registering every folder within the structure and or just registering the top folder and listening or CREATE and MODIFY

There is no direct support for that across platforms. For Windows there is an ExtendedWatchEventModifier.FILE_TREE that will watch a directory recursively. However there is no equivalent functionality on Mac or Linux. Also, note that ExtendedWatchEventModifier is an extension and not part of the standard definition.

You have to listen for CREATE and DELETE. When the object created (deleted) is a directory you need to add (remove) a new watch on the subdirectory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM