Skip to content

Instantly share code, notes, and snippets.

@atomAltera
Last active January 3, 2016 14:19
Show Gist options
  • Save atomAltera/8475599 to your computer and use it in GitHub Desktop.
Save atomAltera/8475599 to your computer and use it in GitHub Desktop.
Simple Java Watch Service implementation
import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
public class T_Watcher {
public static void main(String[] args) throws IOException {
Path target_path = Paths.get(args.length > 0 ? args[0] : "/");
WatchService w_serv = FileSystems.getDefault().newWatchService();
WatchKey w_key = target_path.register(w_serv, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
do {
for (WatchEvent<?> event : w_key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW) continue;
kind = (WatchEvent.Kind<Path>)kind;
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path filename = ev.context();
if (kind == ENTRY_CREATE)
System.out.println("Created: " + filename);
else if (kind == ENTRY_DELETE)
System.out.println("Deleted: " + filename);
else if (kind == ENTRY_MODIFY)
System.out.println("Modifed: " + filename);
}
} while (w_key.reset());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment