Skip to main content

Monitor File Changes

· One min read

Open in Notion

public static void main(String[] args) throws Exception {

WatchService watchService = FileSystems.getDefault().newWatchService();

Path path = Paths.get("G:\\");

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:" + event.kind() + ", File:" + event.context());
}
key.reset();
}
}

WatchService added in Java7 for NIO solution.