File Change Notification is a new feature added in JDK 7. It is a part of the new file system API (NIO 2.0). It uses the WatchService API to receive file change notification events like creation, modification, and deletion of files or directories.
Following are the steps required to monitor the notification events:
WatchService
WatchService service = FileSystems.getDefault().newWatchService();
Path path = Paths.get(dir);
path.register(watchService,StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
take()
while(true) { WatchKey key = service.take(); ... }
for (WatchEvent event : key.pollEvents()) { System.out.println(event.kind() + ": "+ event.context()); } boolean valid = key.reset(); if (!valid) { break; }
Following is the complete java code:
import java.nio.*; import java.io.*; import java.nio.file.StandardWatchEventKinds.*; import java.nio.file.*; public class FileChangeNotifier { public static void main(String args[]) throws IOException, InterruptedException { watchDir("E:\\MyFolder"); // Monitor changes to the files in E:\MyFolder } public static void watchDir(String dir) throws IOException, InterruptedException { WatchService service = FileSystems.getDefault().newWatchService(); // Create a WatchService Path path = Paths.get(dir); // Get the directory to be monitored path.register(service, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); // Register the directory while(true) { WatchKey key = service.take(); // retrieve the watchkey for (WatchEvent event : key.pollEvents()) { System.out.println(event.kind() + ": "+ event.context()); // Display event and file name } boolean valid = key.reset(); if (!valid) { break; // Exit if directory is deleted } } } }
The File Change Notification feature provides a simple and elegant way of monitoring file notification events.