Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java nio WatchService for multiple directories

Tags:

java

java-7

nio

I want to watch (monitor) multiple directories using Java NIO WatchService. My problem here is the number of directories to watch is dynamic and the user can add any number of directories to the WatchService. Is this achievable?

like image 267
G.S Avatar asked Mar 20 '13 07:03

G.S


2 Answers

It is possible to register multiple paths with the same WatchService. Each path gets its own WatchKey. The take() or poll() will then return the WatchKey corresponding to the path that was modified.

See Java's WatchDir example for details.

like image 78
henko Avatar answered Sep 22 '22 07:09

henko


Following the same link as in previous answers: Oracle WatchDir.

You can create first the WatchService:

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

At this point you can add many paths to the same WatchService:

Path path1 = Paths.get("full\path\1\\");
path1.register(watchService,
               StandardWatchEventKinds.ENTRY_CREATE);

Path path2 = Paths.get("full\path\2\\");
path2.register(watchService,
               StandardWatchEventKinds.ENTRY_CREATE);

Then you can manage the events as follow:

WatchKey key;
while ((key = watchService.take()) != null) {
    for (WatchEvent<?> event : key.pollEvents()) {
        System.out.println(
          "Event kind:" + event.kind() 
            + ". File affected: " + event.context() + ".");
    }
    key.reset();
}

Now, if you want to get more information about where was raised the event, you can create a map to link the key and the path by example (You can consider create the variable as class level following your needs):

Map<WatchKey, Path> keys;

In this example you can have the paths inside a list, then you need to loop into it and add each path to the same WatchService:

for (Path path : paths) {
    WatchKey key = path.register(
            watchService,
            StandardWatchEventKinds.ENTRY_CREATE);
    keys.put(key, path);
}

Now to manage the events, you can add something like it:

WatchKey key;
while ((key = watchService.take()) != null) {
    Path path = keys.get(key);
    // More code here.
    key.reset();
}
like image 36
Jairo Martínez Avatar answered Sep 23 '22 07:09

Jairo Martínez