How do you use WatchService (file watchers) with a simple code example?

The Java NIO (New I/O) package includes a way to watch for changes in files and directories using the WatchService API. This feature is extremely useful for applications that need to respond to changes in the file system, such as editors, backup utilities, and configuration watchers.

Using WatchService in Java

The WatchService API allows you to register directories for watching and respond to events like creation, modification, and deletion of files. Below is a simple example of how to use WatchService in Java.


import java.nio.file.*;

public class FileWatcherExample {
    public static void main(String[] args) {
        try {
            // Create a WatchService
            WatchService watchService = FileSystems.getDefault().newWatchService();
            Path path = Paths.get("path/to/watch"); // Specify the path to watch
            path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                                      StandardWatchEventKinds.ENTRY_MODIFY,
                                      StandardWatchEventKinds.ENTRY_DELETE);

            System.out.println("Watching directory: " + path);

            while (true) {
                // Wait for a watch key to be available
                WatchKey key = watchService.take();
                for (WatchEvent> event : key.pollEvents()) {
                    WatchEvent.Kind> kind = event.kind();

                    // Retrieve the file name associated with the event
                    WatchEvent ev = (WatchEvent) event;
                    Path fileName = ev.context();

                    System.out.println(kind.name() + ": " + fileName);
                }
                // Reset the key to receive further events
                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
    

Java WatchService file watcher NIO file system directory monitoring