Directory listener in Java

Jinith picture Jinith · Feb 9, 2011 · Viewed 34.4k times · Source

I have an application in which I want to listen to any changes made to a particular directory. The application should ping me as soon as there are any files added, deleted or updated in that directory.

Answer

rene picture rene · Jul 15, 2013

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);
        }