How to monitor file or directory changes?

package org.kodejava.io;

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("F:/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

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 to SrinCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.