Java 7 nio WatchService
我正在使用以下方法观看目录。
Path myDir = Paths.get("/rootDir");
try {
WatchService watcher = myDir.getFileSystem().newWatchService();
myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey watckKey = watcher.take();
List<WatchEvent<?>> events = watckKey.pollEvents();
for (WatchEvent event : events) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("Created: " + event.context().toString());
JOptionPane.showMessageDialog(null,"Created: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("Delete: " + event.context().toString());
JOptionPane.showMessageDialog(null,"Delete: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
System.out.println("Modify: " + event.context().toString());
JOptionPane.showMessageDialog(null,"Modify: " + event.context().toString());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.toString());
}
但是上述方法只响应目录中发生的一个事件,之后该观察者不响应该文件夹中发生的事件。有没有办法可以修改它以捕获文件夹内发生的所有事件。我还想修改它以捕获子文件夹中发生的事件。有人可以帮我吗。
谢谢你。