Java › I/O & NIO
How would you use the WatchService API (java.nio.file) to monitor a directory for file system changes (creation, modification, deletion) in real time?
IntermediateAnswer
WatchService (obtained via FileSystem.newWatchService()) lets you register a directory Path for specific event types (ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE), then repeatedly call watchService.take() (blocking until an event occurs) or poll() (non-blocking) to receive a WatchKey containing the actual list of events that occurred since the last poll -- commonly used for building file-watching features like a hot-reload development tool, an automated file-processing pipeline that reacts to new files appearing in a drop folder, or a configuration file that should be reloaded automatically when modified.
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Path.of("watched-folder");
dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
WatchKey key = watcher.take(); // blocks until a change occurs
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println(event.kind() + ": " + event.context());
}
key.reset(); // MUST call reset() to continue receiving further events for this key
}Real-world example A batch-processing service watches a designated drop folder using WatchService, automatically triggering processing logic the moment a new file appears, rather than needing to inefficiently poll the directory's contents on a fixed timer to check for new files.