30 March 2009

Java7 Directory Listener



I guess everyone had a need to monitor a directory for file creation/update sometime. Previously we used to accomplish this task by continiously polling files in the target directory such as

while(true){
File [] allFiles = dir.listFiles();
processList(allFiles);
waitForSomeTime();
}


Now we have a new way of doing the same task in an event driven manner.
see java.nio.file package for handy FileSystem,FileRef,Watchable,WatchEvent and WatchService.

Here is a sample for how to do the above task with new Java7 APIs.

WatchService service = FileSystems.getDefault().newWatchService();
WatchKey key = directory.getPath().register(service,new Kind[]{StandardWatchEventKind.ENTRY_CREATE});
while(true){
key=service.take();
List eventList = key.pollEvents();
...
key.reset();

}

No comments: