How to monitor file or directory changes?

package org.kodejava.example.nio;

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

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

public class FileWatchDemo {
    public static void main(String[] args) {
        try {
            //
            // Creates a instance of WatchService.
            //
            WatchService watcher = FileSystems.getDefault().newWatchService();

            //
            // Registers the logDir below with a watch service.
            //
            Path logDir = Paths.get("D:\Temp\logs");
            logDir.register(watcher,
                    ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);

            //
            // Monitor the logDir at listen for change notification.
            //
            while (true) {
                WatchKey key = watcher.take();
                for (WatchEvent event : key.pollEvents()) {
                    WatchEvent.Kind kind = event.kind();

                    if (kind == ENTRY_CREATE) {
                        System.out.println("Entry was created on log dir.");
                    } else if (kind == ENTRY_MODIFY) {
                        System.out.println("Entry was modified on log dir.");
                    } else if (kind == ENTRY_DELETE) {
                        System.out.println("Entry was deleted from log dir.");
                    }
                }
                key.reset();
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.
Wayan Saryada

2 Comments

  1. Found this a very useful example to understand watchservice..

    In the SOP, I added event.context() to know what file has changed.

    if (kind == ENTRY_CREATE) {
        System.out.println("Entry was created on log dir.:" + event.context());
    } else if (kind == ENTRY_MODIFY) {
        System.out.println("Entry was modified on log dir.:" + event.context());
    } else if (kind == ENTRY_DELETE) {
        System.out.println("Entry was deleted from log dir.:" + event.context());
    }
    
  2. I apologize ; In your next article i see the example to know the file name.

    ((Path)event.context()).getFileName();
    

    Thanks for your examples.

Leave a Reply