Directory listener in Java

Since Java 1.7 you can use the Watch Service API to register for directory events. It is part of Java’s New I/O (NIO) library and does not require any additional resources. An example how to use the API can be found in the official documentation.

After registering the WatchService you can retrieve events for the target path like this:

for (WatchEvent<?> event: key.pollEvents()) {
             // Context for directory entry event is the file name of entry
            WatchEvent<Path> ev = cast(event);
            Path name = ev.context();
            Path child = dir.resolve(name);

            // print out event
            System.out.format("%s: %s\n", event.kind().name(), child);
        }

Leave a Comment