Monitor a Folder using Java
Consider a scenario such that we 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.
To implement this scenario, 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
WatchService and Watchable provides the framework to watch registered object for changes using Java. 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.
File : MonitorFolder
Following program, 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 include our business service, such as to read the file or send an email.
public class MonitorFolder
public static void main(String arg) throws IOException,InterruptedException
Path fileFolder = Paths.get("./file/");
WatchService watchService = FileSystems.getDefault().newWatchService();
fileFolder.register(watchService, NTRY_CREATE, ENTRY_DELETE,ENTRY_MODIFY);
boolean valid = true;
WatchKey watchKey = watchService.take();
for (WatchEvent<?> event : watchKey.pollEvents())
String fileName = event.context().toString();
System.out.println("File Created:" + fileName);
valid = watchKey.reset();
} while (valid);