Tuesday, March 17, 2020

How to monitor or watch folder for file creation , deletion and update using java

In past for requirement where in whenever any file is created or updated or deleted if we want to perform some action we need to either go to JMS, RabbitMQ etc options. Other option was to have write our own event handling. But in JDK7 and above we get inbuilt NIO package that come with WatchService and WatchKey concept. Using WatchKey we register the service on folder which we want to watch for event like create/delete/modifyi.e.
Path faxFolder = Paths.get("C:\\Latest_JAVA_eclipse_WorkSpace\\ConvertValue\\src\\fax");
WatchService watchService = FileSystems.getDefault().newWatchService();
WatchKey key = faxFolder.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);

code:-
import java.io.IOException;
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;
public class SiddhuDirchange {
public static void main(String[] args) throws Exception {
Path faxFolder = Paths.get("C:\\Latest_JAVA_eclipse_WorkSpace\\ConvertValue\\src\\fax");
WatchService watchService = FileSystems.getDefault().newWatchService();
WatchKey key = faxFolder.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
boolean valid = true;

do {

for (WatchEvent event : key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
System.out.println("File Created:");
key.reset();
}
if (StandardWatchEventKinds.ENTRY_DELETE.equals(event.kind())) {
System.out.println("File delete:");
key.reset();
}
if (StandardWatchEventKinds.ENTRY_MODIFY.equals(event.kind())) {
System.out.println("File modifies:");
key.reset();
}

}
//Dont forget to reset the key.
valid = key.reset();
} while (valid);
}
}
Note: to get the file name you can use
String fileName = event.context().toString();
System.out.println("File Name for create/update/delete:" + fileName);

No comments: