How to get the file name when using WatchService?

package org.kodejava.example.nio;

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

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

public class WatchServiceGetFilename {
    public static void main(String[] args) {
        try {
            //
            // Create a WatchService and register the logDir path with the
            // WatchService for ENTRY_CREATE.
            //
            WatchService watcher = FileSystems.getDefault().newWatchService();
            Path logDir = Paths.get("D:\Temp\logs");
            logDir.register(watcher, ENTRY_CREATE);

            while (true) {
                WatchKey key = watcher.take();
                for (WatchEvent event : key.pollEvents()) {
                    if (event.kind() == ENTRY_CREATE) {
                        //
                        // Get the name of created file.
                        //
                        WatchEvent ev = (WatchEvent) event;
                        Path filename = ev.context();

                        System.out.printf("A new file %s was created.%n",
                                filename.getFileName());
                    }
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Wayan Saryada

I am a programmer, a runner, an open water diver and currently living in the island of Bali, Indonesia. If you need help on Java programming you can hire me on Fiverr.

Leave a Comment.