Monitor Directory Changes in Java NIO 2 | WatchService Example in Java NIO 2

By Arvind Rai, December 03, 2013
Java NIO 2 provides the API which monitors the given directory. Directory creation, deletion, changing the name of directory or creating any file or directory inside any directory, all can be observed efficiently with WatchService and Watchable of the java.nio.file API which has been introduced in JDK 7. In this way to monitor any file or directory creation, deletion or updation is now very easy with the help of this NIO 2 API. We also say it JDK 7 Observer pattern. Now we will go through all those methods, classes and interfaces which will participate in monitoring the directory changes in java.

Monitor Directory Changes in Java NIO 2 | WatchService Example in Java NIO 2

WatchService in Java NIO 2

java.nio.file.WatchService has been introduced in JDK 7. WatchService has the responsibility to watch all the registered objects for their changes. Only watchable object should be registered with watch service to monitor the changes. Watchable object has the register method to register itself. After registering, it returns WatchKey and getting a watch key means the object has been registered successfully. Now understand the two methods of WatchService.

poll() : poll is retrieve and delete the data and return null if not available.
take() : take is retrieve and delete and wait if not present.

When any change in watchable object takes place, the watch key is signaled and is stored in queue later which will be poll or take by watch service. Once the change event has been processed, the watch key is reset. And again it is ready to get signal and to be stored in queue. Watch service is thread safe i.e more than one thread can access watch service.

Watchable in Java NIO 2

java.nio.file.Watchable has been introduced in JDK 7. Watchable objects are registered with watch service. java.nio.file.Path is the Watchable entity. Path extends Watchable interface. In our example, we will create watchable object as Path instance. Watchable has register method as given below.
WatchKey register(WatchService wservice, WatchEvent.Kind<?>... events)

WatchKey in Java NIO 2

java.nio.file.WatchKey interface has been introduced in JDK 7. WatchKey behaves as a token which is retuned by register method of watchable object. WatchKey has three states.

ready: When created then ready state.
signalled When any change takes place, then watch key is signaled and goes into queue for poll or take.
reset: once the changes are processed, watch key is reset to receive new signal.
WatchKey has the following methods.
cancel(): registration with watch service can be canceled using cancel() method.
isValid(): checks watch key to be valid.
pollEvents(): pending events are polled for the watch key and List is maintained and processed.
reset(): Watch key is reset to receive new signal.
watchable() : returns the watchable object related to that watch key.

WatchEvent and StandardWatchEventKinds in Java NIO 2

WatchEvent is an event kind that serves the identification purpose. It has two methods two get name and type. java.nio.file.StandardWatchEventKinds has static fields that returns WatchEvent.Kind. Find the fields of StandardWatchEventKinds .

ENTRY_CREATE: Create directory event and a watch key is stored in queue.
ENTRY_DELETE Delete directory event and a watch key is stored in queue.
ENTRY_MODIFY Modify directory event and a watch key is stored in queue.
OVERFLOW: When events are lost, OVERFLOW indicates for that failure.
FileSystem.newWatchService() in Java NIO
WatchService instance is created by FileSystem. FileSystem has a method as newWatchService that returns WatchService object.

Example to Monitor Directory Changes in Java
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;
public class WatchServiceExample {
       public static void main(String[] args) throws IOException, InterruptedException {
              Path path = Paths.get("D:/cp");
              FileSystem fileSystem = FileSystems.getDefault();
              WatchService watchService = fileSystem.newWatchService();
              path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_MODIFY,
                WatchKey watchKey = watchService.take();
                List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
                for (WatchEvent<?> we: watchEvents){
                     if(we.kind() == StandardWatchEventKinds.ENTRY_CREATE){
                            System.out.println("Created: "+we.context());
                     }else if (we.kind() == StandardWatchEventKinds.ENTRY_DELETE){
                            System.out.println("Deleted: "+we.context());
                     } else if(we.kind() == StandardWatchEventKinds.ENTRY_MODIFY){
                            System.out.println("Modified :"+we.context());
In our example we have taken a directory as path variable. FileSystem is returning WatchService. Then our watchable object i.e path calls the register method to be registered with watch service. We are observing all the three events create, delete and update by passing StandardWatchEventKinds fields. In an infinite loop, we call the watch service take() method to get the watch key. And then watch key calls the pollEvents() that returns WatchEvent. And then this list has been iterated to log the directory changes.
Create and delete some directory and file in your given path. And output will be like as below.
Deleted: New folder
Created: test
Deleted: test
Created: New
Modified :New

©2024 | Privacy Policy | Contact Us