Search code examples
javaniojava-7

Java nio WatchService for multiple directories


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?


Solution

  • 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.