diff options
| author | Szymon Szukalski <szymon.szukalski@gmail.com> | 2012-10-01 13:35:00 +1000 |
|---|---|---|
| committer | Szymon Szukalski <szymon.szukalski@gmail.com> | 2012-10-01 13:35:00 +1000 |
| commit | 6a16552fd38a91076169466328763cf541027e31 (patch) | |
| tree | 826659a21331ef9e9cc9b0ee48f27456caa3a0c1 /src/main/java/io/skas/melbjvm/nio2/Watcher.java | |
initial commit
Diffstat (limited to 'src/main/java/io/skas/melbjvm/nio2/Watcher.java')
| -rw-r--r-- | src/main/java/io/skas/melbjvm/nio2/Watcher.java | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/src/main/java/io/skas/melbjvm/nio2/Watcher.java b/src/main/java/io/skas/melbjvm/nio2/Watcher.java new file mode 100644 index 0000000..2947ef7 --- /dev/null +++ b/src/main/java/io/skas/melbjvm/nio2/Watcher.java @@ -0,0 +1,53 @@ +package io.skas.melbjvm.nio2; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.nio.file.*; + +public class Watcher { + + private static final Logger LOG = LoggerFactory.getLogger(Watcher.class); + + public void watchDirectory(Path watchedPath) throws IOException, InterruptedException { + + try (WatchService watchService = FileSystems.getDefault().newWatchService()) { + + final WatchKey key = watchedPath.register( + watchService, + StandardWatchEventKinds.ENTRY_CREATE, + StandardWatchEventKinds.ENTRY_MODIFY, + StandardWatchEventKinds.ENTRY_DELETE); + + while (true) { + + watchService.take(); + + for (WatchEvent<?> watchEvent : key.pollEvents()) { + final WatchEvent.Kind<?> kind = watchEvent.kind(); + + // handle OVERFLOW event + if (kind == StandardWatchEventKinds.OVERFLOW) { + continue; + } + + final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; + Path newFile = watchedPath.resolve(watchEventPath.context()); + + if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { + new FileReader(newFile); + } + } + + //reset the key + boolean valid = key.reset(); + + //exit loop if the key is not valid (if the directory was deleted, for example) + if (!valid) { + break; + } + } + } + } +} |
