Java Directory monitor for changes

Introduction

Types of watch events

WatchEvent Description
OVERFLOWAn event that has overflown (ignore)
ENTRY_CREATE A directory or file was created
ENTRY_DELETE A directory or file has been deleted
ENTRY_MODIFYA directory or file has been modified
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.concurrent.TimeUnit;

public class Main {

   public static void main(String[] args) {
      try {//  w w  w  .j a  v a 2  s  .  c  o  m
         System.out.println("Watch Event, press q<Enter> to exit");
         FileSystem fileSystem = FileSystems.getDefault();
         WatchService service = fileSystem.newWatchService();
         Path path = fileSystem.getPath(".");
         System.out.println("Watching :" + path.toAbsolutePath());
         path.register(service, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
               StandardWatchEventKinds.ENTRY_MODIFY);
         boolean shouldContinue = true;
         while (shouldContinue) {
            WatchKey key = service.poll(250, TimeUnit.MILLISECONDS);

            // Code to stop the program
            while (System.in.available() > 0) {
               int readChar = System.in.read();
               if ((readChar == 'q') || (readChar == 'Q')) {
                  shouldContinue = false;
                  break;
               }
            }
            if (key == null)
               continue;
            for (WatchEvent<?> event : key.pollEvents()) {
               if (event.kind() == StandardWatchEventKinds.OVERFLOW)
                  continue;
               WatchEvent<Path> ev = (WatchEvent<Path>) event;
               Path filename = ev.context();
               System.out.println("Event detected :" + filename.toString() + " " + ev.kind());
            }
            boolean valid = key.reset();
            if (!valid) {
               break;
            }
         }
      } catch (IOException | InterruptedException e) {
         e.printStackTrace();
      }

   }

}



PreviousNext

Related