Sunday, August 23, 2009

Listen to file changes

Ever wanted your program to register changes happening to a file without writing much code? Apache VFS is here to help you with that!

public class SampleFileListener {

 public static void main(String[] args) {
  try {
   // FileSystemManager manages the file system
   FileSystemManager fsm = VFS.getManager();
   // FileSystemManager instance is used to get a FileObject instance
   // for the file to which you wish to listen. Here, the changes on 
   // the file temp.txt directly under D: would be registered.
   FileObject fileObject = fsm.resolveFile("D:\\temp.txt");
   // DefaultFileMonitor is the object which would monitor the file. 
   // The javadoc says that the class is a Thread based polling system 
   // monitor with 1 second delay. This means when the start method on
   // an instance of DefaultFileMonitor is invoked, a new Thread is 
   // started in the background which checks the file for changes after
   // every second. An instance of an anonymous inner class extending the
   // FileListener is passed to the constructor of DefaultFileMonitor. Its
   // the methods of this class that gets triggered every time a change
   // is detected by the file monitor.
   DefaultFileMonitor dfm = new DefaultFileMonitor(new FileListener() {
    // Method invoked when the file is changed and saved.
    public void fileChanged(FileChangeEvent arg0) throws Exception {
     System.out.println("File changed");

    public void fileCreated(FileChangeEvent arg0) throws Exception {
     System.out.println("File created");

    public void fileDeleted(FileChangeEvent arg0) throws Exception {
     System.out.println("File deleted");
   // Add the file object to the monitor and start the process of listening
   // for changes.
   // Setup the main thread to run infinitely for live monitoring of changes 
   // on the file.
   while(true) {}
  } catch (FileSystemException e) {

The above program is all that you need for registering changes on a file in your file system. No need for writing your own custom thread or file monitors. For the above class to compile and run successfully, you would need to add the VFS jar to the CLASSPATH. Download it from here. You would also need to add commons-logging.jar (version 1.0.4 or later) to the CLASSPATH.

No comments:

Post a Comment