Monitoring a Directory for Content Changes - Java File Path IO

Java examples for File Path IO:File Watcher

Introduction

Use a WatchService to subscribe to be notified about events occurring within a folder.

Types of watchEvents

WatchEvent Description
OVERFLOW An event that has overflown (ignore)
ENTRY_CREATE A directory or file was created
ENTRY_DELETE A directory or file has been deleted
ENTRY_MODIFY A directory or file has been modified

Demo Code

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 .  ja 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);
        while (System.in.available() > 0) {
          int readChar = System.in.read();
          if ((readChar == 'q') || (readChar == 'Q')) {
            shouldContinue = false;
            break;
          }
        }
        if (key == null)
          continue;
        key.pollEvents()
            .stream()
            .filter(
                (event) -> !(event.kind() == StandardWatchEventKinds.OVERFLOW))
            .map((event) -> (WatchEvent<Path>) event)
            .forEach(
                (ev) -> {
                  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();
    }
  }
}

Result


Related Tutorials