Monitor a Directory for Changes using Java

Many applications which we use on a day to day basis like a music organizer, file editors monitor the directory for any changes in the files/directories and take appropriate action in the application if there are any changes detected on the fly. Since Java do not have direct access to the system level calls (unless we use JNI, which will make the code platform specific) the only way to monitor any directory is to use a separate thread which will be using a lot of resources (memory & disk I/O) to monitor the changes inside the directory. If we have sub-directories and need a recursive monitor, then the thread becomes more resource intensive.

There was a JSR (Java Specification Request) requested to add / rewrite more I/O APIs for Java platform. This was implemented in JDK 7 as JSR 203 with support for APIs like file system access, scalable asynchronous I/O operations, socket-channel binding and configuration, and multicast datagrams.

JSR 203 is one of the big feature for JDK 7 (Developer Preview is available in java.sun.com) and its been implemented as the second I/O package is java, called as NIO.2. I will be looking into more of these packages in future posts, but in this, I will show how to monitor a directory and its sub-directories for any changes using NIO.2 (JDK 7).

The APIs which we will be using WatchService (a watch service that watches registered objects for changes and events), WatchKey (a token representing the registration of a watchable object with a WatchService) and WatchEvent (an event or a repeated event for an object that is registered with a WatchService) to monitor a directory. So, without further explanation, let’s start working on the code.

Please note that you need JDK 7 to run this program. While writing this post, JDK 7 is available as a EA (Early Access) in Java Early Access Downloads page. Download the JDK and install it.

The first step is to get a directory to monitor. Path is one of the new I/O API as a part of NIO.2 which gives us more control over the I/O. So let’s get the directory to watch, if you want to watch the directory recursively then there should be another boolean flag defined, but in this example we will watch only the parent directory.

Path _directotyToWatch = Paths.get(args[0]);

Now let’s create a Watch service to the above directory and add a key to the service. In the watch key we can define what are all the events we need to look for. In this example we will monitor Create, Delete & Rename/Modify of the files or directories in the path.

WatchService watcherSvc = FileSystems.getDefault().newWatchService();
WatchKey watchKey = _directotyToWatch.register(
    watcherSvc,ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

Now we have all the variables defined. Let’s start a infinite loop to monitor the directory for any changes using WatchEvent. We will poll events in the directory and once some event is triggered (based on the WatchKey definition) we will print the type of event occurred and the name of the file/directory on which the event occurred. Once done, we will reset the watch key.

while (true) {
    watchKey=watcherSvc.take();
    for (WatchEvent<?> event: watchKey.pollEvents()) {
        WatchEvent<Path> watchEvent = castEvent(event);
        System.out.println(event.kind().name().toString() + " "
            + _directotyToWatch.resolve(watchEvent.context()));
    watchKey.reset();
    }
}

Now to make the WatchEvent <Path> work, we should create a small utility as below ( this is the castEvent which is used in the above code).

static <T> WatchEvent<T> castEvent(WatchEvent<?> event) {
    return (WatchEvent<T>)event;
}

Now compile the file and give a directory as a runtime parameter while running it. Once the program starts running, start creating some directories/files or modify/rename some files in the directory which you gave as a parameter, the program will start triggering the event and you should be able to watch the modifications in the console. A sample output from my machine is below.

Full source of this application is available in my github page.

import java.nio.file.*;
import static java.nio.file.StandardWatchEventKind.*;

static <T> WatchEvent<T> castEvent(WatchEvent<?> event) {
    return (WatchEvent<T>)event;
}

public static void main (String args[]) throws Exception {
    Path _directotyToWatch = Paths.get(args[0]);
    WatchService watcherSvc = FileSystems.getDefault().newWatchService();
    WatchKey watchKey = _directotyToWatch.register(watcherSvc,
        ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

    while (true) {
        watchKey=watcherSvc.take();
        for (WatchEvent<?> event: watchKey.pollEvents()) {
            WatchEvent<Path> watchEvent = castEvent(event);
            System.out.println(event.kind().name().toString() + " "
                + _directotyToWatch.resolve(watchEvent.context()));
            watchKey.reset();
        }
    }
}



Venish Joe Clarence avatar
I have the ability to arrange 1's and 0's in such an order that an x86 processor can actually interpret and execute those commands. I make the world a better place by writing mindless back-end programs that no-one will ever see nor even know that it's there. But I know; and that's all that matters. -Alucard