From 6ddaaf8555d6b94684d061289249cac67c6eb09f Mon Sep 17 00:00:00 2001 From: Szymon Szukalski Date: Wed, 3 Oct 2012 10:45:23 +1000 Subject: Added example of SimpleFileVisitor usage --- src/main/java/io/skas/melbjvm/nio2/Watcher.java | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) (limited to 'src/main/java/io/skas/melbjvm/nio2/Watcher.java') diff --git a/src/main/java/io/skas/melbjvm/nio2/Watcher.java b/src/main/java/io/skas/melbjvm/nio2/Watcher.java index 1938c9f..c3986a7 100644 --- a/src/main/java/io/skas/melbjvm/nio2/Watcher.java +++ b/src/main/java/io/skas/melbjvm/nio2/Watcher.java @@ -13,11 +13,12 @@ public class Watcher { private static final Logger LOG = LoggerFactory.getLogger(Watcher.class); - public void watchDirectory(Path watchedPath) throws IOException, InterruptedException { + public void watchDirectory(Path directory) throws IOException, InterruptedException { + // New try with resources try (WatchService watchService = FileSystems.getDefault().newWatchService()) { - final WatchKey key = watchedPath.register( + final WatchKey key = directory.register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, @@ -25,21 +26,29 @@ public class Watcher { while (true) { + // retrieve and remove the next watch key (waits) watchService.take(); + // get list of events for the key for (WatchEvent watchEvent : key.pollEvents()) { + + // get the event kind final WatchEvent.Kind kind = watchEvent.kind(); + // get the filename for the event + final WatchEvent watchEventPath = (WatchEvent) watchEvent; + final Path filename = watchEventPath.context(); + + LOG.debug("event: {} filename: {}", kind, filename); + // handle OVERFLOW event if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } - final WatchEvent watchEventPath = (WatchEvent) watchEvent; - Path newFile = watchedPath.resolve(watchEventPath.context()); - + // handle CREATE event if (kind == StandardWatchEventKinds.ENTRY_CREATE) { - new AsynchronousFileReader(newFile); + new AsynchronousFileReader(filename); } } -- cgit v1.2.3