Skip to main content

Lesson 5 of 8

WatchService - Monitoring File Changes

java.nio.file.WatchService lets you monitor a directory for file creation, modification, and deletion events - without polling. This enables reactive file-based workflows: auto-reload configs, process new uploads, watch log files.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Directory Watching

Directory Watching
import java.io.*;
import java.nio.file.*;

public class WatchServiceDemo {

    public static void watchDirectory(Path dir) throws IOException, InterruptedException {
        System.out.println("Watching: " + dir.toAbsolutePath());

        try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
            // Register directory - which events to watch
            dir.register(watcher,
                StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE
            );

            while (true) {
                WatchKey key = watcher.take();  // blocks until event

                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();

                    if (kind == StandardWatchEventKinds.OVERFLOW) {
                        System.out.println("Event overflow - some events missed");
                        continue;
                    }

                    @SuppressWarnings("unchecked")
                    WatchEvent<Path> pathEvent = (WatchEvent<Path>) event;
                    Path changed = dir.resolve(pathEvent.context());

                    System.out.printf("[%s] %s%n", kind.name(), changed);

                    // React to specific events
                    if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                        if (changed.toString().endsWith(".csv")) {
                            processNewCsvFile(changed);
                        }
                    }
                }

                boolean valid = key.reset();  // MUST reset - re-enables the key
                if (!valid) {
                    System.out.println("Directory no longer accessible");
                    break;
                }
            }
        }
    }

    static void processNewCsvFile(Path file) {
        System.out.println("Auto-importing new CSV: " + file.getFileName());
        // CsvOperations.importCatalog(file)
    }

    public static void main(String[] args) throws Exception {
        Path watchDir = Path.of("library/imports");
        Files.createDirectories(watchDir);
        watchDirectory(watchDir);  // runs until interrupted
    }
}

Quick Quiz

Tip

Tip

Practice WatchService Monitoring File Changes in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for WatchService - Monitoring File Changes

Practice Task

Note

Practice Task - (1) Write a working example of WatchService Monitoring File Changes from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with WatchService Monitoring File Changes is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/8 done