Reputation: 30097
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
Upvotes: 1
Views: 1729
Reputation: 454
We need to register the Folder F1 and all of it subFolders F11 and F12 recursively. And the solution is provided in the official doc itself.
Here's the code segment you need to recursivly folder F1 and all of its subfolder to watchService:
/**
* Register the given directory and all its sub-directories with the WatchService.
*/
private void registerAll(final Path start) throws IOException {
// register directory and sub-directories
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
return FileVisitResult.CONTINUE;
}
});
}
Incase of more details or incase you dont understand the usage of this code segment. refer to official doc. links provided below.
Official Doc Ref:
https://docs.oracle.com/javase/tutorial/essential/io/notification.html
https://docs.oracle.com/javase/tutorial/essential/io/examples/WatchDir.java
Upvotes: 0
Reputation: 279890
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 Path
s 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.
Upvotes: 3