Search code examples
javaniowatchservice

How do I unregister a directory from Java watchservice?


I registered a folder to my watchService:

path.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

Later on, I want to cancel this registration. I know that I somehow need to tell the watchService which WatchKey I want to cancel. What's the correct function to accomplish this?


Solution

  • You have the information in the Watchable interface javadoc that provides the method to register a Watchable object (such as a Path instance)


    public interface Watchable

    This interface defines the register method to register the object with a WatchService returning a WatchKey to represent the registration. An object may be registered with more than one watch service. Registration with a watch service is cancelled by invoking the key's cancel method.


    So you have just to do :

    WatchKey watchKey = path.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    ...
    watchKey.cancel();