# WatchService interface

In 
Published 2024-01-07

This tutorial explains what is and how to WatchService interface in Java.

WatchService watches registered objects for changes and events.

Please take a look at the following example which is self-explanatory:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

@SpringBootApplication
public class Demo1Application {

    public static void main(String[] args) throws IOException, InterruptedException {
        SpringApplication.run(Demo1Application.class, args);

        // Create a Watch Service
        WatchService watchService = FileSystems.getDefault().newWatchService();

        // Define a directory
        Path path = Paths.get("D:\\test-java\\my-dir");

        // Register a directory with the Watch Service (which is looking for create/modify/delete
        // operations on that directory files)
        path.register(watchService,
                StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE
                );

        // A pointer to a WatchKey object is defined, but we don't have such an object yet.
        WatchKey watchKey;

        // When a WatchKey event is queued, we do something
        while ((watchKey = watchService.take()) != null) {
            watchKey.pollEvents().stream().forEach(event -> {
                System.out.println("------------------------");
                System.out.println(event.context() + "--> " +event.kind());
            });

            // Reset the key in order to be ready to receive other changes.
            watchKey.reset();
        }
	}
}

When we run the code we can see something like that (if you add text3.txt file, modify and delete it):

------------------------
text3.txt--> ENTRY_CREATE
------------------------
text3.txt--> ENTRY_MODIFY
------------------------
text3.txt--> ENTRY_DELETE

More information about NIO (NIO2) you have here.