实现说明
逻辑集中在类 InboxWatcher里。
while ((key = watcher.poll(1, TimeUnit.SECONDS)) != null) 反复执行,循环体之外没有别的重复。资源写在 try 头部,关闭由编译器生成、异常安全。
常见问题
「WatchService 目录事件监听」这个示例怎么运行?
直接执行即可——程序只依赖运行时自身。
核心语句
Path inbox = Files.createTempDirectory("inbox");
Files.writeString(note, "hello again");
Path note = inbox.resolve("note.txt");
代码示例
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.concurrent.TimeUnit;
public class InboxWatcher {
public static void main(String[] args) throws IOException, InterruptedException {
Path inbox = Files.createTempDirectory("inbox");
try (WatchService watcher = inbox.getFileSystem().newWatchService()) {
inbox.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
// 注册之后再产生变更,事件才会被捕获
Path note = inbox.resolve("note.txt");
Files.writeString(note, "hello");
Files.writeString(note, "hello again");
Files.deleteIfExists(note);
// poll 带超时:不永久阻塞;处理完必须 reset,否则后续事件不再投递
WatchKey key;
while ((key = watcher.poll(1, TimeUnit.SECONDS)) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println(event.kind() + ": " + event.context());
}
key.reset();
}
}
}
}