How do I unregister a directory from Java watchservice?

送分小仙女□ 提交于 2019-12-11 02:08:42

问题


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?


回答1:


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();



回答2:


The register method returns the WatchKey, as described in the documentation, which has a cancel() method.



来源:https://stackoverflow.com/questions/43950919/how-do-i-unregister-a-directory-from-java-watchservice

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