Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.