Created
April 7, 2014 03:56
-
-
Save trevorc/10014623 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.nio.file.FileSystems; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.nio.file.WatchEvent; | |
import java.nio.file.WatchKey; | |
import java.nio.file.WatchService; | |
import java.util.List; | |
import java.util.function.Consumer; | |
import java.util.stream.Stream; | |
import static java.util.stream.Collectors.toList; | |
import static java.nio.file.StandardWatchEventKinds.*; | |
public final class Watcher { | |
private static final WatchEvent.Kind<?>[] WATCH_EVENTS = { | |
ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY}; | |
private final Path mWatchDirectory; | |
public Watcher(Path watchDirectory) { | |
mWatchDirectory = watchDirectory; | |
} | |
public void watch(final Consumer<WatchEvent<?>> consumer) throws IOException { | |
try (WatchService watchService = FileSystems.getDefault().newWatchService()) { | |
mWatchDirectory.register(watchService, WATCH_EVENTS); | |
WatchKey key; | |
do { | |
key = watchService.take(); | |
key.pollEvents().forEach(consumer); | |
} while (key.reset()); | |
} catch (InterruptedException e) { | |
throw new IOException(e); | |
} | |
} | |
public static void main(String... args) throws IOException { | |
if (args.length != 1) throw new IllegalArgumentException("usage: java Watcher DIR"); | |
new Watcher(Paths.get(args[0])).watch(event -> System.out.format( | |
"%s %s\n", event.kind(), event.context())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment