我使用下面的方法使用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());
}
但是,上述方法只響應一個事件發生在目錄後,觀察者沒有響應該文件夾中發生的事件。有沒有辦法可以修改這個來捕獲文件夾內發生的所有事件。我也想修改它來捕獲子文件夾中發生的事件。有人可以幫助我。
謝謝。
這是捕獲像一個文本文件中改變內容的事件? – Sajirupee
不,它會檢查是否在給定的目錄中創建或刪除任何新文件 –
它還將檢查是否有任何新文件在子文件夾 –