How to get the file name when using WatchService?


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("/Users/kodejava/temp");
            logDir.register(watcher, ENTRY_CREATE);

            while (true) {
                WatchKey key;
                try {
                    key = watcher.take();
                } catch (InterruptedException e) {

                for (WatchEvent<?> event : key.pollEvents()) {
                    if (event.kind() == ENTRY_CREATE) {
                        // Get the name of created file.
                        WatchEvent<Path> ev = cast(event);
                        Path filename = ev.context();

                        System.out.printf("A new file %s was created.%n",
        } catch (IOException e) {

    private static <T> WatchEvent<T> cast(WatchEvent<?> event) {
        return (WatchEvent<T>)event;

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳


  1. How to get the location of the filename when monitoring a folder and its subfolders. Please help with sample code to do the same.

    • Hello Amrita,

      Use the following snippet to get the full location of the file name.

      Path directory = (Path) key.watchable();
      Path fullPath = directory.resolve(ev.context());
      System.out.printf("A new file %s was created.%n", fullPath);

Leave a Reply

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