实现说明
行为都写在 RecursiveTreeWatcher中。
文件的主干是一个循环——for (WatchEvent<?> event : key.pollEvents())。不需要 finally——try 头部声明的资源按相反顺序自行关闭。失败路径是显式的——守卫条件成立就抛出 IllegalStateException。
常见问题
输入不合法时代码会怎么表现?
代码会抛出 IllegalStateException。请在调用点处理,或有意让它向上传播。
「WatchService 递归监视目录树」这个示例怎么运行?
运行这个文件就行;脚本没有任何外部要求。
核心语句
throw new IllegalStateException("no events captured");
代码示例
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 RecursiveTreeWatcher {
public static void main(String[] args) throws IOException, InterruptedException {
Path root = Files.createTempDirectory("tree-watch");
try (WatchService watcher = root.getFileSystem().newWatchService()) {
root.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
// create the subdirectory after registering the root: its ENTRY_CREATE gets captured
Path topic = root.resolve("topic");
Files.createDirectories(topic);
WatchKey key = watcher.poll(1, TimeUnit.SECONDS);
if (key == null) {
throw new IllegalStateException("no events captured");
}
for (WatchEvent<?> event : key.pollEvents()) {
Path created = root.resolve(((WatchEvent<Path>) event).context());
System.out.println(event.kind() + ": " + created);
// re-register a directory when its ENTRY_CREATE arrives:
// WatchService never watches new directories on its own; without this their events never arrive
if (Files.isDirectory(created)) {
created.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
}
}
key.reset();
// topic is registered now: file events inside it arrive too
Files.writeString(root.resolve("a.txt"), "root file");
Files.writeString(topic.resolve("b.txt"), "nested file");
while ((key = watcher.poll(1, TimeUnit.SECONDS)) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
Path dir = (Path) key.watchable();
Path child = dir.resolve(((WatchEvent<Path>) event).context());
System.out.println(event.kind() + ": " + child);
}
key.reset();
}
}
}
}