Sunday, June 15, 2014
Today in this article I will discuss with an amazing feature of Java7. Here I will show you how to create a file/folder watcher/watch service. In other words I will actually write Java code which will be able to monitor a file/folder/directory for changes. This will require Java 7 NIO .2. This monitoring service is very useful in many applications like IDE. Also this can be used for hot deployment in servers. Monitoring or watching a folder for changes means that whenever there is a change in file system associated with the folder then an event is triggerd. The event is catched and associated change is extracted to know what change has occurred and based on that different actions can be taken.
Below are the steps you must follow to implement watch service
   1. Get the path of the folder - The first step is to get the Path object associated with the folder. This is done using Paths.get() method.
   2. Get file system of the path - Next step is to get the FileSystem object associated with the Path object. This is done using getFileSystem() method.
   3. Get watch service - Next you have to get WatchService from FileSystem object using newWatchService() method.

   4. Register to watch service and events - In this step you will have to register the Path object to the watch service created. With that you will also have to mention all the events that you want to monitor. There are four events ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW. This is done using register() method.
   5. Start infinite loop - You will have top start the infinite loop to watch the folder continously.
       5a. Poll the events for watch key - Inside the loop you will have to poll for events using pol() or take() methods. Though there are two poll methods but its is better sometimes to use take method as it waits until an event occurs, whereas for poll methods they return null value so you have to keep a null check otherwise NullPointer Exception will be thrown.
       5b. Retrieve pending events - Next you have to retrieve the pending events. There can be more than one event, so use a for loop and get events from WatchKey. Depending on event take necessary actions.
       5c. Reset the key - Next reset the key and wait for next events using reset() method.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.nio.file.FileSystem;
import java.nio.file.Path;
import static java.nio.file.StandardWatchEventKinds.*;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchService;
import java.util.concurrent.TimeUnit;

public class FolderMonitor {
 /**
  * Monitors a folder for changes
  * @param path Path to be monitored
  * @throws Exception
  */
 public void monitor(Path path) throws Exception{
  FileSystem fs = path.getFileSystem();  //get file system
  try(WatchService ws = fs.newWatchService()){  //get watch service in try block
   //register for events to warch service
   path.register(ws, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
   System.out.println("Watching : "+path);
   while(true){  //poll loop
    final WatchKey key = ws.take();  //wait and get watch key
    for(WatchEvent<?> we : key.pollEvents()){
     final Kind<?> kind = we.kind();  //get event kind
     if(kind == OVERFLOW)
      return;
     else if(kind == ENTRY_CREATE)
      printEvent("New path created", we);
     else if(kind == ENTRY_DELETE)
      printEvent("Path deleted", we);
     else if(kind == ENTRY_MODIFY)
      printEvent("Path modified", we);
    }
    if(!key.reset())  //reset
     break;
   }
  }
 }
 
 /**
  * Displays event occurred
  * @param desc  Description of event
  * @param we  watch event
  */
 private void printEvent(String desc, WatchEvent<?> we){
  System.out.println(desc+" : "+((WatchEvent<Path>)we).context());
 }
 
 public static void main(String[] args) throws Exception {
  FolderMonitor fm = new FolderMonitor();
  fm.monitor(Paths.get("C:/demo"));
 }
}
-------------------------------------------------------------------------------------------------------------------------
Download Links 
-------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared

0 comments:

Post a Comment

Total Pageviews

Followers


Labels

Popular Posts

free counters