Monitoring file Changes in a Directory Using Java

Explore how to leverage Java’s WatchService API for real-time file and directory monitoring. Learn with full code examples and detailed explanations
E
EdToks3:17 min read
Monitoring file Changes in a Directory Using Java

In this article will learn about Watchservice API in java and how it simplifies to monitor real time file changes using java.

Java provides a powerful and flexible mechanism for monitoring file system events, such as changes to files and directories. This is achieved through the WatchService API, which is part of the java.nio.file package.

Overview of the WatchService API

The WatchService API allows you to register a directory (or directories) with the watch service. When a file in a registered directory is created, deleted, or modified, the watch service will be notified.

Creating a WatchService

First, you need to create an instance of WatchService. This can be done using the FileSystems class, like so:

WatchService watchService = FileSystems.getDefault().newWatchService();

Registering a Directory

Next, you need to register a directory with the WatchService. You can do this using the register method on a Path instance, like so:

Path path = Paths.get("/directory-path");
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

In this example, we’re registering the directory for three types of events: file creation (ENTRY_CREATE), file deletion (ENTRY_DELETE), and file modification (ENTRY_MODIFY).

Processing Events

Finally, you need to continuously poll the WatchService for events and process them as they occur. This can be done in a loop, like so:

while (true) {
    WatchKey key = watchService.take();
    for (WatchEvent<?> event : key.pollEvents()) {
        WatchEvent.Kind<?> kind = event.kind();
        if (kind == StandardWatchEventKinds.OVERFLOW) {
            continue;
        }
        WatchEvent<Path> ev = (WatchEvent<Path>) event;
        Path fileName = ev.context();
        System.out.println(kind.name() + ": " + fileName);
    }
    boolean valid = key.reset();
    if (!valid) {
        break;
    }
}

In this loop, we’re taking the next available WatchKey from the WatchService, polling it for events, and then processing each event. If the WatchKey is no longer valid (i.e., the directory is inaccessible), we break out of the loop.

Please replace "directory-path" with the actual directory path you want to monitor. Also, remember to handle exceptions appropriately in your production code.

Now, let's stich together and check full working example below:

import java.nio.file.*;

public class DirectoryWatcher {
    public static void main(String[] args) {
        try {
            WatchService watchService = FileSystems.getDefault().newWatchService();
            Path path = Paths.get("/path/to/directory"); // change to exact directory path to monitory file changes
            
            path.register(
                watchService, 
                StandardWatchEventKinds.ENTRY_CREATE, 
                StandardWatchEventKinds.ENTRY_DELETE, 
                StandardWatchEventKinds.ENTRY_MODIFY
            );

            while (true) {
                WatchKey key = watchService.take();
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                    if (kind == StandardWatchEventKinds.OVERFLOW) {
                        continue;
                    }
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path fileName = ev.context();
                    System.out.println(kind.name() + ": " + fileName);
                }
                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

In this code:

  • We first create a WatchService and register a directory path with it.

  • We then start an infinite loop where we continuously poll the WatchService for new events.

  • When an event occurs, we check its type and print a message accordingly.

Please replace "/path/to/directory" with the actual directory path you want to monitor. Also, remember to handle exceptions appropriately in your production code.

If you like this content. Please support us, by sharing with your friends and social media. to reach more people.

Let's keep in touch!

Subscribe to keep up with latest updates. We promise not to spam you.