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("/Users/kodejava/temp/");
            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 (ENTRY_CREATE.equals(kind)) {
                        System.out.println("Entry was created on log dir.");
                    } else if (ENTRY_MODIFY.equals(kind)) {
                        System.out.println("Entry was modified on log dir.");
                    } else if (ENTRY_DELETE.equals(kind)) {
                        System.out.println("Entry was deleted from log dir.");
                    }
                }
                key.reset();
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

To get the created, modified or deleted file you can see the following example: How to get the file name when using WatchService?.

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

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.

Leave a Reply