During the past few months, I have chances to work in projects which have the requirement to monitor a specific folder on the filesystem for changes and act accordingly (e.g import structured file from a FTP upload folder). The following solutions I found useful to fulfill the above requirements:
jNotify
- Pros: easy to use, cross-platform (kind of, because jNotify author has developed native code implementation for 3 platforms: Windows, Linux, and MacOS X), can be used with Java 1.4+
- Cons: there are a few limitations on each platform as noted on its website.
I’ve got a problem when I tried to run it on a Ubuntu 64bit machine, but after searching on their forum on sourceforge, I’ve found my solutions (by recompiling the native code). I’ve used it in production since then and it never failed me. But there is a catch: when you move files/folders into your monitored folders, it won’t detect the event as new files/folders created. I think it’s because Linux only updates (and not creates) the inodes of those files/folders on the ext4 filesystem. In order for your Java application to pickup the native code, you have to put the native library (.so for Linux, .dll for Windows) in the folder specified by the system property java.library.path
JPathWatch
- Pros: cross-platform (including Windows, Linux, MacOS X and FreeBSD), the native library is bundled inside the distribution jar so all you have to do is including its jar in the classpath.
- Cons: the API is a little hard to use (the author do not use the observer pattern due to the scalability), requires Java 5+
WatchService in JDK 7
- Pros: built-in in standard distribution of Java 7, no other external libraries or native code is required.
- Cons: you have to use Java 7, of course. This sometimes is a showstopper in various projects, although Java 6 is about to reach EOL (in November this year)
You can download all the sample code at https://bitbucket.org/tinhtruong/blog-samples/src/6d3ce2ac58a8/filesystem-monitoring