File Change Listener


File Change Listener


In this blog, we will learn about file change listener.


Brief Idea

As name suggest, File Change Listener is responsible for listening change events occur on file system.
We will use apache common JCI (Java Compiler Interface)  to implement our file change listener. Click here for more Information about JCI

Here is the package : org.apache.commons.jci.monitor
Following interface and class will be used for our file listener purpose :
  • FilesystemAlterationListener : It is an interface.It acts as a listener that receives events of file system modifications.
  • FilesystemAlterationMonitor : It is a class. Its a runnable that spawns of a monitoring thread triggering the observers and managing their listeners. 


FileChangeListenerExample.java


package com.sarf.Listener;
import java.io.File;
import org.apache.commons.jci.monitor.FilesystemAlterationListener; 
import org.apache.commons.jci.monitor.FilesystemAlterationMonitor;
import org.apache.commons.jci.monitor.FilesystemAlterationObserver;

public class FileChangeListenerExample implements 
  FilesystemAlterationListener 
{ 
  private FilesystemAlterationMonitor fileAlterMonitorObj 
   = new FilesystemAlterationMonitor();
  File file = null;
   
  FileChangeListenerExample(){}
  FileChangeListenerExample(File file)
  {
   this.file = file;
  }
    
  public void attachListenerToFile()
  {
   fileAlterMonitorObj.addListener(file, this);
  }
   
  public void startListening()
  {
   fileAlterMonitorObj.start();
   fileAlterMonitorObj.setInterval(100);
  }
   
  @Override
  public void onDirectoryChange(File arg0) {
  }
  @Override
  public void onDirectoryCreate(File arg0) {
  }
  @Override
  public void onDirectoryDelete(File arg0) {
  }
  @Override
  public void onFileChange(File arg0) {
    System.out.println("File Changed");
  }
  @Override
  public void onFileCreate(File arg0) {
  }
  @Override
  public void onFileDelete(File arg0) {
  }
  @Override
  public void onStart(FilesystemAlterationObserver arg0) {
  }
  @Override
  public void onStop(FilesystemAlterationObserver arg0) {
  }
}



Use Listener
package com.sarf.Listener;
import java.io.File;

public class FileListenerUser 
{ 
 public static void main(String[] args) 
 {
  File file = new File("K:\\test.txt");
  FileChangeListenerExample objFCL = new FileChangeListenerExample(file);
  objFCL.attachListenerToFile();
  objFCL.startListening();
 } 
}




To download Apache Commons JCI API (commons-jci-fam-1.0.jar), click here    


 You can modify this example and make it as directory change listener. you have to do two things here.First, pass directory path name K:\\testDir in place of  'K:\\test.txt' file name to the FileChangeListenerExample constructor.Second, override onDirectoryXXXX() methods to perform your required operation.

Comments are closed.