lunedì 29 settembre 2014

java File Watcher

With the new features of java 7 was introduced the WatchService class, with it we know all action done on the watched folder.
But there isn't an implementation that permits to watch a single file so.. follows a my implementation called FileWatcher:

import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;

public class FileWatcher implements Runnable{

 private final WatchService watcher;
 private Path fileToWatch;
 
 
 public FileWatcher(String filePath) throws IOException {
  Path path = Paths.get(filePath);
  this.fileToWatch = path.getFileName();
  path.getParent().register(watcher, ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY);
 }

 @Override
 public void run() {
  for (;;) {
   
   // wait for key to be signaled
      WatchKey key;
      try {
          key = watcher.take();
      } catch (InterruptedException x) {
          return;
      }
      
      for (WatchEvent event: key.pollEvents()) {
          WatchEvent.Kind kind = event.kind();

          if (kind == OVERFLOW) continue;
          
          // The filename is the
          // context of the event.
          @SuppressWarnings("unchecked")
          Path fileName = ((WatchEvent)event).context();
             
          if(!fileName.equals(fileToWatch))
              continue;
             
          if(kind == ENTRY_CREATE) create();
             
          if(kind == ENTRY_DELETE) delete();             
     
          if(kind == ENTRY_MODIFY) modify();
     
      }

      // Reset the key -- this step is critical if you want to
      // receive further watch events.  If the key is no longer valid,
      // the directory is inaccessible so exit the loop.
      boolean valid = key.reset();
      if (!valid) {
          break;
      }
  }
 }

 public void modify() {}
 
 public void delete() {}
 
 public void create() {}
 
}

An example of use:

new Thread(new FileWatcher(filePath){
               @Override
               public void modify() {
                  System.out.println("modified");
               }
           }).start();