0Pricing
Java Academy · Lesson

WatchService: Monitoring File Changes

Register a WatchService to detect file creation, modification, and deletion events in real time.

What is WatchService?

WatchService monitors a directory for file system events: creation, modification, and deletion. It uses OS-level notifications (inotify on Linux, FSEvents on macOS) — much more efficient than polling.

import java.nio.file.*;

WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Path.of("/home/user/watched");

dir.register(watcher,
    StandardWatchEventKinds.ENTRY_CREATE,
    StandardWatchEventKinds.ENTRY_MODIFY,
    StandardWatchEventKinds.ENTRY_DELETE
);
System.out.println("Watching: " + dir);

Polling for Events

Call watcher.take() to block until an event occurs, then process the events:

while (true) {
    WatchKey key;
    try {
        key = watcher.take(); // blocks until events arrive
    } catch (InterruptedException e) {
        break;
    }
    
    for (WatchEvent<?> event : key.pollEvents()) {
        WatchEvent.Kind<?> kind = event.kind();
        Path changed = ((WatchEvent<Path>) event).context();
        System.out.println(kind.name() + ": " + changed);
    }
    
    key.reset(); // must reset to receive further events
}

All lessons in this course

  1. Path: Representing File Locations
  2. Files Utility: Read, Write, Copy, Move
  3. Walking Directory Trees with Files.walk
  4. WatchService: Monitoring File Changes
← Back to Java Academy