Quantcast
Channel: Michael Vorburger's Blog v2
Viewing all articles
Browse latest Browse all 64

Java 7 WatchService-based DirectoryWatcher implementation

$
0
0
When as part of my HoTea framework (otherwise unrelated to this post) I was looking for a simple Java utility to watch for and be notified about file changes in a given directory, I found that Java 7+ comes with a native / OS level file change notification WatchService API. Unfortunately it’s very “low level” and one cannot easily do something like this with it (using a Java 8 lambda expression instead of classic anonymous inner class for the listener):

new DirectoryWatcherBuilder().dir(dir).listener(
 (directory, changeKind) -> System.out.println(
      changeKind.toString() + "" + directory.toString()));

So I wrote it, see my DirectoryWatcher (created by DirectoryWatcherBuilder, implemented by DirectoryWatcherImpl, tested by DirectoryWatcherTest), currently part of HoTea - perhaps this is useful to others as well. Leave a comment here if it is, or better send a pull request against the project if you find anything worth enhancing or fixing (directory rename handling probably needs a bit more work).

PS: Apache Commons IO FileMonitor is something similar, but it uses a less effective approach of polling files from a background thread, instead of the Java 7 JDK's WatchService. (And Apache Commons VFS also seems to have another implementation of something very similar.) Google Guava does not yet seem to have such a utility. Larger frameworks like Spring integration, Apache Camel & Co. probably have similar utilities.

Viewing all articles
Browse latest Browse all 64

Trending Articles