Monitoring file events using WatchEvents - Java File Path IO

Java examples for File Path IO:File Watcher

Description

Monitoring file events using WatchEvents

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.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class Main {

    public static void main(String[] args) {
        try {//from   w w w .  ja  v a  2  s .com
            FileSystem fileSystem = FileSystems.getDefault();
            WatchService watchService = fileSystem.newWatchService();
            Path directory = Paths.get("/home/docs");
            WatchEvent.Kind<?>[] events = {
                StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_MODIFY};
            directory.register(watchService, events);
            while (true) {
                System.out.println("Waiting for a watch event");
                WatchKey watchKey = watchService.take();

                System.out.println("Path being watched: " + watchKey.watchable());
                System.out.println();

                if (watchKey.isValid()) {
                    for (WatchEvent<?> event : watchKey.pollEvents()) {
                        System.out.println("Kind: " + event.kind());
                        System.out.println("Context: " + event.context());
                        System.out.println("Count: " + event.count());
                        System.out.println();
                    }

                    boolean valid = watchKey.reset();
                    if (!valid) {
                        // The watchKey is not longer registered
                    }
                }
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

    }
}

The fields of this interface are summarized in the following table:

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

Related Tutorials