Java nio WatchService for multiple directories
Following the same link as in previous answers: Oracle WatchDir.
You can create first the WatchService
:
WatchService watchService = FileSystems.getDefault().newWatchService();
At this point you can add many paths to the same WatchService
:
Path path1 = Paths.get("full\path\1\\");
path1.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE);
Path path2 = Paths.get("full\path\2\\");
path2.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE);
Then you can manage the events as follow:
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println(
"Event kind:" + event.kind()
+ ". File affected: " + event.context() + ".");
}
key.reset();
}
Now, if you want to get more information about where was raised the event, you can create a map to link the key and the path by example (You can consider create the variable as class level following your needs):
Map<WatchKey, Path> keys;
In this example you can have the paths inside a list, then you need to loop into it and add each path to the same WatchService
:
for (Path path : paths) {
WatchKey key = path.register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE);
keys.put(key, path);
}
Now to manage the events, you can add something like it:
WatchKey key;
while ((key = watchService.take()) != null) {
Path path = keys.get(key);
// More code here.
key.reset();
}
It is possible to register multiple paths with the same WatchService
. Each path gets its own WatchKey
. The take()
or poll()
will then return the WatchKey
corresponding to the path that was modified.
See Java's WatchDir example for details.