0
當使用此代碼時,目錄觀察工作正常,但它只會更新文件日期修改至少一分鐘,這對我來說不夠快,如果我垃圾郵件f5在文件夾中刷新它,代碼可以看到所有的變化 - 幾乎是即刻,我希望觀察者在沒有任何用戶輸入的情況下完成我的想法,也許可以通過文件大小進行監視(但我沒有找到檢查大小的條目)?因爲字節大小是一個很大的問題的錯誤讀通過後,筆者刪除其他想法目錄觀察延遲
public class DirectoryWatchDemo {
public static void main(String[] args) {
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get("C:\\Program Files (x86)\\logs");
dir.register(watcher, new WatchEvent.Kind[]{StandardWatchEventKinds.ENTRY_MODIFY}, SensitivityWatchEventModifier.HIGH);
System.out.println("Watch Service registered for dir: " + dir.getFileName());
while (true) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
@SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();
System.out.println(kind.name() + ": " + fileName);
if (kind == ENTRY_MODIFY &&
fileName.toString().equals("console.log")) {
System.out.println("My source file has changed!!!");
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}