Thursday, 10 September 2015

Java 7 - NIO - Watcher implementation

One of the new features of Java7 was NIO package. 
Java NIO also known as new input output library as is a set of classes defined under package java.nio.* to access files, file attributes and file systems.

The main classes from this package are:
  • Path - to manage file location and directory hierarchy
  • Files - to manage file operations
Some functionalities that can be implemented are:
  • Walking the file tree
  • Watchers - monitoring the creation/modification/deletion of files
  • Copy/Create/Delete files from a directory(atomic operations with synchronization)
  • Find files using matcher expressions
In the following example we are going to see how to implement a watcher. This is useful when we need a process to monitor when a file is created/modified or deleted in a directory.

Steps in this example:
1- watch for new files in a directory
2- evaluate the mime type of the file
3- if it is a text file it will be copied to other directory.

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class Watcher{
public static void main(String[] args) {
Path folder = Paths.get("C:/Users/user/workspace/TEST1");
Path destination = Paths.get("C:/Users/user/workspace/TEST2");
Watcher watcher = new Watcher();
watcher.watchDirectoryPath(folder, destination);
}
public void watchDirectoryPath(Path path, Path destination) {
FileSystem fs = path.getFileSystem ();
try(WatchService service = fs.newWatchService()) {
path.register(service, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key = null;
while(true) {
key = service.take();
Kind<?> kind = null;
for(WatchEvent<?> watchEvent : key.pollEvents()) {
kind = watchEvent.kind();
if (StandardWatchEventKinds.OVERFLOW == kind) {
continue;
} else if ( StandardWatchEventKinds.ENTRY_CREATE == kind) {
Path newPath = ((WatchEvent<Path>) watchEvent).context();
if (Files.probeContentType(newPath.getFileName()).equals("text/plain"))
{
Files.copy(path.resolve(newPath), destination.resolve(newPath), StandardCopyOption.REPLACE_EXISTING);
}
}
}
if(!key.reset()) {
break;
}
}
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
view raw Watcher.java hosted with ❤ by GitHub

No comments:

Post a Comment