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

WatchService in Java NIO 2

Watchable in Java NIO 2

WatchKey in Java NIO 2

WatchEvent and StandardWatchEventKinds in Java NIO 2

FileSystem.newWatchService() in Java NIO

Example to Monitor Directory Changes in Java

package com.concretepage.io.file; import java.io.IOException; 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, StandardWatchEventKinds.ENTRY_DELETE); while(true){ 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()); } } if(!watchKey.reset()){ break; } } } }

Deleted: New folder Created: test Deleted: test Created: New Modified :New

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.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 is retrieve and delete the data and return null if not available.: 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.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.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.: When created then ready state.When any change takes place, then watch key is signaled and goes into queue for poll or take.: once the changes are processed, watch key is reset to receive new signal.WatchKey has the following methods.: registration with watch service can be canceled using cancel() method.: checks watch key to be valid.: pending events are polled for the watch key and List is maintained and processed.: Watch key is reset to receive new signal.: returns the watchable object related to that watch key.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 .: Create directory event and a watch key is stored in queue.Delete directory event and a watch key is stored in queue.Modify directory event and a watch key is stored in queue.: When events are lost, OVERFLOW indicates for that failure.WatchService instance is created by FileSystem. FileSystem has a method as newWatchService that returns WatchService object.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.