Java nio WatchService for multiple directories

I want to watch (control) several directories using Java NIO WatchService. My problem is that the number of directories to view is dynamic, and the user can add any number of directories to WatchService. Is it possible?

+5
source share
2 answers

You can register multiple paths with the same WatchService. Each path gets its own WatchKey. Then, take()or poll()return WatchKey, the corresponding path that has been changed.

See the Java WatchDir example for more details .

+6
source

, , WatchService.

, , WatchService 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);

Oracle

+1

All Articles