观看服务 api ( https://docs.oracle.com/javase/tutorial/essential/io/notification.html ) 看起来有点复杂和违反直觉。所以我很困惑如何正确使用它。让我们按照上面网址中的指南进行操作。
WatchService watcher = FileSystems.getDefault().newWatchService();
Paths.get("C:/Path").register(watcher,
ENTRY_CREATE,
ENTRY_DELETE,
ENTRY_MODIFY) //return WatchKey object
register 方法返回 WatchKey 对象。在指南中它通常被省略。它很奇怪。怎么能用?它从寄存器返回的原因是什么?因为获取 WatchKey 的正常方式是这样的:
for (;;) {
// wait for key to be signaled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
//procees all kinds of events there
if (kind == OVERFLOW) {
continue;
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}