Skip to content

Instantly share code, notes, and snippets.

@trevorc
Created April 7, 2014 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trevorc/10014623 to your computer and use it in GitHub Desktop.
Save trevorc/10014623 to your computer and use it in GitHub Desktop.
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