【发布时间】:2015-09-19 21:43:13
【问题描述】:
我需要监视给定目录及其所有子目录的更改(尤其是文件和目录的添加)。
我目前的代码如下
Path watchFolder = Paths.get("D:/watch");
WatchService watchService = FileSystems.getDefault().newWatchService();
watchFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
watchFolder.register(watchService, StandardWatchEventKinds.ENTRY_DELETE);
watchFolder.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
boolean valid = true;
do {
WatchKey watchKey = watchService.take();
for (WatchEvent event : watchKey.pollEvents()) {
WatchEvent.Kind kind = event.kind();
if (StandardWatchEventKinds.ENTRY_CREATE.equals(kind)) {
String fileName = event.context().toString();
System.out.println("File Created:" + fileName);
}
}
valid = watchKey.reset();
} while (valid);
此代码只能监控父目录的变化。如果我在父目录中添加一个目录,它就可以触发事件。但是,如果我在子目录中添加一个文件,它就无法检测到。
仅供参考:我也尝试过 JNotify,但它一直说 java.lang.UnsatisfiedLinkError: no jnotify_64bit in java.library.path
还有比这些更好的解决方案吗?
【问题讨论】:
-
我认为这里已经回答了这个问题:stackoverflow.com/questions/17850940/…
标签: java directory subdirectory jnotify