Monitoring File System Events with Java.nio.file.WatchService

The java.nio.file package provides the WatchService API for monitoring changes to the file system. This tutorial will guide you through using WatchService to detect events like file creation, modification, and deletion.

Prerequisites:

  • Basic understanding of Java programming
  • Familiarity with working with files and directories

Overview of Java WatchService

Java provides the java.nio.file.WatchService interface as part of the NIO (New I/O) package, which allows you to monitor file system events such as file creation, modification, and deletion. This feature is particularly useful for applications that need to react to changes in the file system in real-time. Here’s how you can use WatchService to monitor file system events in Java:

1. Create a WatchService Instance:

First, obtain an instance of WatchService by invoking the FileSystems.getDefault().newWatchService() method.

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

2. Register Directories with the WatchService:

Next, register the directories you want to monitor with the WatchService using the register() method of Path objects.

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

You can specify the types of events you’re interested in (e.g., creation, modification, deletion) as varargs of WatchEvent.Kind.

3. Start Watching for Events:

Use an infinite loop to continuously watch for file system events. Inside the loop, use the take() method of WatchService to block until a key is available, indicating that one or more events have occurred.

while (true) {
    WatchKey key = watchService.take();
    // Process events
}

4. Process Events:

After receiving a key, iterate over the WatchEvent instances associated with the key and handle each event accordingly.

for (WatchEvent<?> event : key.pollEvents()) {
    WatchEvent.Kind<?> kind = event.kind();
    if (kind == StandardWatchEventKinds.OVERFLOW) {
        // Handle overflow event
        continue;
    }
    // Retrieve the file name associated with the event
    WatchEvent<Path> ev = (WatchEvent<Path>) event;
    Path fileName = ev.context();
    // Process the event (e.g., print, notify, etc.)
    System.out.println(kind + ": " + fileName);
}

5. Reset the WatchKey:

After processing the events, reset the WatchKey to continue watching for further events.

boolean valid = key.reset();
if (!valid) {
    // Key is no longer valid (directory inaccessible or deleted)
    // Handle accordingly, e.g., unregister the directory
    break;
}

6. Close the WatchService:

When you’re done watching for events, don’t forget to close the WatchService to release associated resources.

watchService.close();

Complete example

Here’s a complete example demonstrating how to monitor file system events in Java using WatchService:

import java.nio.file.*;

public class FileSystemWatcher {
    public static void main(String[] args) throws Exception {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        Path directory = Paths.get("/path/to/directory");
        directory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

        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 + ": " + fileName);
            }
            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }
        watchService.close();
    }
}

Choose the path which you want to monitor and try, for example, to add a new File in that path:

java monitoring file system changes step-by-step guide

Conclusion

This tutorial should provide a comprehensive guide to getting started with monitoring file system events in Java using WatchService. Let me know if you have any questions or need further clarification!

Found the article helpful? if so please follow us on Socials