Lets think of an use, a java program should monitor a folder and it should alert if a new file is created. We may have a FTP folder where in an external system will post a file and our program has to monitor that FTP folder and when a new file arrives we need to read it or email it.
So we have got the above real time scenarios and how do we solve it using Java? Java version 7 provided an update for IO package. NIO package was a significant update in this version. It has got a set of interfaces and classes to help this job done.
WatchService and Watchable provides the framework to watch registered object for changes using Java. Imagine we have a file editor and it has a file loaded. At the same time, we have opened that same file using another editor and edited it. Now the other editor will alert with a message saying “The file is edited, do you want to load the latest version?”
So to watch this file for changes we can use WatchService and Watchable. Like this we can watch any objects for changes. When we watch files and folder we need to obtain an interface to the underlying native file system. For that we can use the FileSystems class.
Sample Source Code
Following source code, provides implementation for watching a folder for a new file. We obtain the instance of WatchService using the FileSystems class. Then the path to be watched is registered with this instance of WatchService for the CREATE event. When a new file is created we get the event with the context. In this sample, we just get the file name and print it in the console. Here we can fork our business service, like send an email or read the file and store it in database.
com.javapapers.java;
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 MonitorDirectory {
public static void main(String[] args) throws IOException,
InterruptedException {
Path faxFolder = Paths.get("./fax/");
WatchService watchService = FileSystems.getDefault().newWatchService();
faxFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
boolean valid = true;
do {
WatchKey watchKey = watchService.take();
for (WatchEvent<?> event : watchKey.pollEvents()) {
WatchEvent.Kind kind = event.kind();
if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
String fileName = event.context().toString();
System.out.println("File Created:" + fileName);
}
}
valid = watchKey.reset();
} while (valid);
}
}
Create a new file in /ftp/ folder and you can see the output. “ftp” folder should be created in the project root.