41 import java.nio.file.*;
42 import static java.nio.file.StandardWatchEventKinds.*;
43 import static java.nio.file.LinkOption.*;
44 import java.nio.file.attribute.*;
45 import java.io.IOException;
58 @SuppressWarnings(
"unchecked")
59 static <T> WatchEvent<T>
cast(WatchEvent<?> event) {
60 return (WatchEvent<T>)event;
66 private void register(Path dir)
throws IOException {
67 WatchKey key = dir.register(
watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
70 System.out.format(
"register: %s\n", dir);
77 private void registerAll(
final Path start)
throws IOException {
79 Files.walkFileTree(start,
new SimpleFileVisitor<Path>() {
81 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
85 return FileVisitResult.CONTINUE;
94 this.watcher = FileSystems.getDefault().newWatchService();
98 System.out.format(
"Scanning %s ...\n", dir);
100 System.out.println(
"Done.");
119 }
catch (InterruptedException x) {
123 for (WatchEvent<?> event: key.pollEvents()) {
124 WatchEvent.Kind kind =
event.kind();
127 if (kind == OVERFLOW) {
132 WatchEvent<Path> ev =
cast(event);
133 Path
name = ev.context();
134 Path child = ((Path)key.watchable()).resolve(
name);
137 System.out.format(
"%s: %s\n", event.kind().name(), child);
141 if (
recursive && (kind == ENTRY_CREATE)) {
143 if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
146 }
catch (IOException x) {
153 boolean valid = key.reset();
164 System.err.println(
"usage: java WatchDir [-r] dir");
168 public static void main(String[] args)
throws IOException {
170 if (args.length == 0 || args.length > 2)
174 if (args[0].equals(
"-r")) {
182 Path dir = Paths.get(args[dirArg]);