Watch for changes on the filesystem.
make run
On another terminal:
cd d
mkdir d
touch a b d/a
rm a b d/a
rmdir d
The first terminal shows:
ENTRY_CREATE: d
ENTRY_CREATE: a
ENTRY_MODIFY: a
ENTRY_CREATE: b
ENTRY_MODIFY: b
ENTRY_DELETE: a
ENTRY_DELETE: b
ENTRY_DELETE: d
Note how events under d/d were not considered: operation is non-recursive by default.
-
register directories to the watcher service
-
each directory registration returns a key corresponding to that directory
-
watchService.takereturns one of the previously registered keys which has an event.pollis the non-blocking version which may returnnull. -
each key returns events only for the directory on which it was registered.
You cannot get the directory from the key because
key.watchable()returns aWatchable, so you have to keep a map ofkey -> directoryThe only JDK implementation of
Watchablehowever isPath.TODO confirm: So registering the same path multiple times should return equal keys:
final WatchService watchService = FileSystems.getDefault().newWatchService(); final WatchKey key = Paths.get(WATCH_DIR).register( watchService, StandardWatchEventKinds.ENTRY_MODIFY); final WatchKey key2 = Paths.get(WATCH_DIR).register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); assert key.equals(key2);
Not possible: the best you can do is filter the events.
TODO count