如何从 Java watchservice 注销目录?

How do I unregister a directory from Java watchservice?

我向我的 watchService 注册了一个文件夹:

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

稍后,我想取消这个注册。我知道我需要以某种方式告诉 watchService 我想取消哪个 WatchKey。完成此操作的正确函数是什么?

WatchKey的注册方法returns,如documentation, which has a cancel()方法所述。

您在 Watchable 接口 javadoc 中有提供注册 Watchable 对象(例如 Path 实例)方法的信息


public 可观看界面

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.


所以你只需要做:

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