I want to fire an event whenever a file has stopped being modified. I am polling a directory and if the filename matches to "input.csv" then i want to fire an event on that file. Time to check whether the file has been modified is 10 seconds. I am getting a null pointer exception when no event occurs. This is my sample code:
public class MyPoller {
public static void main(String[] args) throws URISyntaxException,
IOException, InterruptedException {
Path tmpPath = Paths.get("E:/MyDirectory/DEC");
WatchService watchService = FileSystems.getDefault().newWatchService();
// Watching the E:/MyDirectory/DEC directory
// for MODIFY and DELETE operations
tmpPath.register(watcput.csvService, StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
for (;;) {
WatchKey key = watchService.poll(10000,TimeUnit.MILLISECONDS);
List<WatchEvent<?>> events = key.pollEvents();
// Poll all the events queued for the key
for (WatchEvent event : events) {
switch (event.context().toString()) {
case "input.csv":
System.out.println("Modified: " + event.context());
String filename = "" + event.context();
System.out.println(" "+filename);
break;
default:
break;
}
}
boolean valid = key.reset();
// If the key is invalid, just exit.
if (!valid) {
break;
}
}
}
}
If no event is generated, then the WatchKey may be null
WatchKey key = watchService.poll(10000,TimeUnit.MILLISECONDS);
Try to do a null
check on the key and then proceed to do pollEvents()
if it's indeed not null
.