Java nio WatchService for multiple directories

核能气质少年 提交于 2019-12-04 21:14:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!