问题
I want to watch (monitor) multiple directories using Java NIO WatchService.
My problem here is the number of directories to watch is dynamic and the user can add any number of directories to the WatchService
. Is this achievable?
回答1:
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.
回答2:
I am just trying to explain how exactly this can be done using WatchService
.
Here is a piece of code that illustrates how you can use one WatchService
instance and listen to two Paths
this.watcher = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<>();
Path plugins = Paths.get(INSTANCE.getPluginPath());
logger.info(String.format("Scanning %s ...", plugins));
registerAll(plugins);
Path drivers = Paths.get(INSTANCE.getDriverPath());
logger.info(String.format("Scanning %s ...", drivers));
registerAll(drivers);
The example is based on Oracle Example
来源:https://stackoverflow.com/questions/15517581/java-nio-watchservice-for-multiple-directories