Java WatchService watch file create, modify and delete events

Introduction

The java.nio.file.StandardWatchEventKinds class defines the standard event types.

Kind MeaningCount
ENTRY_CREATE Directory entry createdAlways a 1
ENTRY_DELETE Directory entry deletedAlways a 1
ENTRY_MODIFY Directory entry modified 1 or greater
OVERFLOW A special event to indicate that events may have been lost or discarded Greater than 1

Register the path with the watch service for create, modify and delete events

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class Main {
  public static void main(String[] args) {
    try (WatchService ws = FileSystems.getDefault().newWatchService()) {
      Path dirToWatch = Paths.get("C:/Java_Dev");

      dirToWatch.register(ws, StandardWatchEventKinds.ENTRY_CREATE,
          StandardWatchEventKinds.ENTRY_MODIFY,
          StandardWatchEventKinds.ENTRY_DELETE);

      System.out.println("Watching " + dirToWatch + " for events.");

      while (true) {
        WatchKey key = ws.take();
        for (WatchEvent<?> event : key.pollEvents()) {
          Kind<?> eventKind = event.kind();
          if (eventKind == StandardWatchEventKinds.OVERFLOW) {
            System.out.println("Event overflow occurred");
            continue;
          }// ww  w .ja  v  a  2  s  .com

          WatchEvent<Path> currEvent = (WatchEvent<Path>) event;
          Path dirEntry = currEvent.context();

          System.out.println(eventKind + " occurred on " + dirEntry);
        }
        // Reset the key
        boolean isKeyValid = key.reset();
        if (!isKeyValid) {
          System.out.println("No longer watching " + dirToWatch);
          break;
        }
      }
    } catch (IOException | InterruptedException e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related