Sunday, November 15, 2015

File Watcher Job Using Apache Common IO

File Watcher Jobs in Java using Apache Commons (JDK1.6)

What is the Objective: we want to invoke something based on some event in our file system, event could be

1. Directory creation/deletion/movement
2. File Creation/deletion/movement

What we are saying here we want to do some activity based on some event happening in the file system, the first thing should ring in our mind, are we looking for some listener ? – Which can listen to the events and respond accordingly.

Yes, that is what I am going to explain you here, the Listener provided by Apache Common library:

org.apache.commons.io.monitor.FileAlterationListener

(Please download the commons.io jars in case you don’t have from here)  

For any Listener three things required:
1.       Listener itself.
2.     The Observer – which will be configured to observe on certain path and based on the event happening in that path, will call the corresponding method of the listener. Apache observer is org.apache.commons.io.monitor.FileAlterationObserver.

3.       The last, one active thread which will have this observer running inside it for any event – Apache active thread is  
org.apache.commons.io.monitor.FileAlterationMonitor

Let’s explore our Apache listener:

What should be the program flow:
1.       Create an implementation for Listener and implement event methods, whichever required
2.       Create and Observer to observer on some path – let’s say (“/temp/”or C:/temp/)
3.       Register our listener with this observer.
4.       Start a Thread and register our observer with it (we call it Monitor)
5.       Done

Code:

1.      Listener:

import java.io.File;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;


public class FileWatcherListenerUsingApache implements FileAlterationListener {

      @Override
      public void onDirectoryChange(File arg0) {
            System.out.println("Directory changed " + arg0.getName() );
           
      }

      @Override
      public void onDirectoryCreate(File arg0) {
            System.out.println("Directory created " + arg0.getName() );
           
      }

      @Override
      public void onDirectoryDelete(File arg0) {
            System.out.println("Directory deleted " + arg0.getName() );
           
      }

      @Override
      public void onFileChange(File arg0) {
            System.out.println("File changed: " + arg0.getName() );
           
      }

      @Override
      public void onFileCreate(File arg0) {
            System.out.println("File craeted " + arg0.getName() );
           
      }

      @Override
      public void onFileDelete(File arg0) {
            System.out.println("File deleted " + arg0.getName() );
           
      }

      @Override
      public void onStart(FileAlterationObserver arg0) {
            System.out.println("Observation started for " + arg0.getDirectory().getAbsolutePath() );
           
      }

      @Override
      public void onStop(FileAlterationObserver arg0) {
            System.out.println("Observation stopped for " + arg0.getDirectory().getAbsolutePath() );
           
      }

}



2.       Observer, Monitor:

import java.io.File;

import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

/***
 * It is used to monitor file system activities on /temp/ directory
 * 
 *
 * @author Sushil
 *
 */
public class FileWatcherObserverUsingApache {

      public static void main(String[] args) throws Exception {
           
            //create file to watch on
            File dirToWatch=new File("/temp/");
           
            // create alteration observer on file
            FileAlterationObserver observer=new FileAlterationObserver(dirToWatch);
           
            // register listener with observer
            observer.addListener(new FileWatcherListenerUsingApache());
           
            // create Monitor ( Thread )
            final FileAlterationMonitor monitor=new FileAlterationMonitor();
           
            // Register Observer with Monitor
            monitor.addObserver(observer);
           
            // Start thread to observe on /temp
            System.out.println("Observation started on :"+ dirToWatch.getAbsolutePath());
            monitor.start();
           
            //
            System.out.println("PRESS CNTL+C to stop");
           
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                  try {
                              monitor.stop();
                        } catch (Exception e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                        }
                }
             });
      }

}


Output:

1.       When started:



2.       Created a new empty file in temp - sushil.txt




3.       Create a directory: sushil




4.       Moved Sushil.txt into sushil directory:




No comments: