javaniowatchservice

How to watch multiple directories with WatchService?


I don't understand, how does

watcher.take();

will know about which directory to report? Does it report about each directory it was registered against?

dir.register(watcher...

If I have multiple watchers, will they report only about those directories, which were registered against them?

What is the purpose of return value of register()? It looks like it never used in description here: http://docs.oracle.com/javase/tutorial/essential/io/notification.html


Solution

  • You use a Path to register a file located by that Path to a WatchService.

    If an event occurs, it will be enqueued in the WatchService and you can retrieve it with take(). take() has no idea about the actual Path.

    Yes, a WatchService will only report events for those Paths registered with it.

    You can use the WatchKey returned by the register method to compare against the WatchKey returned by take(). You can also, obviously, do all the things described in the javadoc.