System.out.println("scanning from: " + path.toAbsolutePath() + '/');
} else {
System.out.println("add: /" + path + '/');
}
parents.push(path);
WatchKey key = path.register(
watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW);
map.put(key, path);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
System.out.println("add: /" + path);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.out.println("visitFileFailed: " + file);
throw exc;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (exc != null) {
System.out.println("postVisitDirectory failed: " + dir);
throw exc;
}
parents.pop();
return FileVisitResult.CONTINUE;
}
};
Files.walkFileTree(rootPath, visitor);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
Files.createDirectory(rootPath.resolve("tmp"));
Files.createDirectory(rootPath.resolve("tmp/dir"));
Files.createFile(rootPath.resolve("tmp/file"));
Files.createFile(rootPath.resolve("tmp/dir/file2"));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
for (;;) {
// retrieve key
WatchKey key = watcher.take();
Path parent = map.get(key);
System.out.println("-----");
// process events
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind().type() == Path.class) {
Path path = (Path) event.context();
Path resolved = parent.resolve(path);
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("cre: /" + resolved);
parents.push(parent);
Files.walkFileTree(resolved, visitor);
parents.pop();
} else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
System.out.println("mod: /" + resolved);
} else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("del: /" + resolved);
} else {
assert false : "Unknown event type: " + event.kind().name();
}
} else {
assert event.kind() == StandardWatchEventKinds.OVERFLOW;
System.out.print(event.kind().name() + ": ");
System.out.println(event.count());
}
}
// reset the key
boolean valid = key.reset();
if (!valid) {
// object no longer registered
map.remove(key);
}
}