Writing a simple file monitor in Java using Commons IO

In this article I am going to show you how to write a simple file monitor. So even though Java 7 comes with a low-level API to watch for file system changes (article here), fow now we will be using using the Commons IO library from the Apache Foundation, mainly the org.apache.commons.io.monitor package.

The first step will be to define the location that we are going to monitor. For this I’ve created a temporary folder of my desktop, and defined a String constant pointing to that newly created location:

The next step will be to define a polling interval: how often we will “look” for file-system changes. The value is expressed in milliseconds:

Now we will have to build a File object out of the folder we are monitoring:

At this point Commons IO comes into picture. In order to make the system monitor actually work we will need at least one instance of the following: FileAlterationObserver, FilterAlterationMonitor and FileAlterationListenerAdaptor .

And then we will proceed to add the listener to the observer, add the observer to the monitor, and start the monitor:

After compiling & running the resulting code, every change I do in the folder that I monitor is being recorded:

The full sourcecode for the simple file monitor: Read More