}
}
private static void watch(){
try {
while (true) {
final WatchKey key = watchService.take();
if(key == null){
continue;
}
for (WatchEvent<?> watchEvent : key.pollEvents()) {
final WatchEvent.Kind<?> kind = watchEvent.kind();
//忽略无效事件
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
//path是相对路径(相对于监控目录)
final Path contextPath = watchEventPath.context();
LOG.debug("contextPath:"+contextPath);
//获取监控目录
final Path directoryPath = directories.get(key);
LOG.debug("directoryPath:"+directoryPath);
//得到绝对路径
final Path absolutePath = directoryPath.resolve(contextPath);
LOG.debug("absolutePath:"+absolutePath);
LOG.debug("kind:"+kind);
//判断事件类别
switch (kind.name()) {
case "ENTRY_CREATE":
if (Files.isDirectory(absolutePath, LinkOption.NOFOLLOW_LINKS)) {
LOG.info("新增目录:" + absolutePath);
LOG.info("Create directory:" + absolutePath, Locale.ENGLISH);
//为新增的目录及其所有子目录注册监控事件
registerTree(absolutePath);
}else{
LOG.info("新增文件:" + absolutePath);
LOG.info("Create file:" + absolutePath, Locale.ENGLISH);
}
break;
case "ENTRY_DELETE":
LOG.info("删除:" + absolutePath);
LOG.info("Delete:" + absolutePath, Locale.ENGLISH);
break;
}
}
boolean valid = key.reset();
if (!valid) {
LOG.info("停止监控目录:"+directories.get(key));
directories.remove(key);
if (directories.isEmpty()) {
LOG.error("退出监控");