Processing WatchEvents from a WatchKey
You'll learn how to extract and handle individual file system change events from a WatchKey using pollEvents().
Once you've obtained a WatchKey from polling your WatchService, the real work begins: examining what actually changed. The WatchKey acts like a mailbox full of event notifications—you need to open it and read each message individually.
Retrieving Events with pollEvents()
The pollEvents() method returns a List<WatchEvent<?>> containing all the events that triggered this WatchKey. Each WatchEvent represents a single file system change (creation, modification, or deletion).
WatchKey key = watchService.poll();
if (key != null) {
List<WatchEvent<?>> events = key.pollEvents();
for (WatchEvent<?> event : events) {
// Process each individual event
WatchEvent.Kind<?> kind = event.kind();
// Get the affected file/directory
Path changedPath = (Path) event.context();
System.out.println("Event: " + kind + " for " + changedPath);
}
key.reset(); // Essential: rearm the key for future events
}
Understanding WatchEvent Components
Each WatchEvent provides:
kind(): The type of change (ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE)context(): The relative path of the affected file (cast toPath)count(): How many times this event occurred (usually 1, but can be higher if events were coalesced)
The Critical reset() Call
After processing events, you must call key.reset() to signal the key is ready to receive new events. Without this, the key becomes inactive and you'll miss future changes.
Key Takeaway: Use pollEvents() to retrieve the list of file system changes from a WatchKey, iterate through each WatchEvent to examine what changed, and always call reset() afterward to continue monitoring.