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

A programmer, a slow runner, a recreational open water diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

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());
    }
    
    Reply
    • I apologize ; In your next article i see the example to know the file name.

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

      Thanks for your examples.

      Reply

Leave a Reply