Skip to content

Instantly share code, notes, and snippets.

@prateeknischal
Created December 11, 2019 18:20
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 prateeknischal/d397fba1c7baeb990d620a3fdcc2f6d8 to your computer and use it in GitHub Desktop.
Save prateeknischal/d397fba1c7baeb990d620a3fdcc2f6d8 to your computer and use it in GitHub Desktop.
Directory watcher in java7
import java.nio.file.WatchService;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.FileSystems;
public class DirectoryWatcherExample {
public static void main(String[] args) throws Exception {
WatchService watchService
= FileSystems.getDefault().newWatchService();
Path path = Paths.get(".");
path.register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println(
"Event kind:" + event.kind()
+ ". File affected: " + event.context() + ".");
}
key.reset();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment