The new java.nio.file classes
The watcher
The watcher can watch one or more directories. The directory has to be registered with the watcher, then when an event occirs a key is released. This key gives details of the event .
- Create a path object that refers to the directory that you want to watch
[sourcecode language=”java” toolbar=”false”]
Path dir = Paths.get("E:/Development/CodeSource/java7/test");
[/sourcecode]
- Create a new watch service
[sourcecode language=”java” toolbar=”false”]
WatchService watcher = FileSystems.getDefault().newWatchService();
WatchService watcher = dir.getFileSystem().newWatchService();
[/sourcecode]
- Register directory with the watcher(mutiple directories can be registered)
[sourcecode language=”java” toolbar=”false”]
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
[/sourcecode]
- Get the watch key (the application waits here until an event occurs)
[sourcecode language=”java” toolbar=”false”]
WatchKey watckKey = watcher.take();
[/sourcecode]
- When an event occurs we poll it and then treat it
[sourcecode language=”java” toolbar=”false”]
for (WatchEvent<?> event: key.pollEvents()) {}
[/sourcecode]
- To get the type of event
[sourcecode language=”java” toolbar=”false”]
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {}
[/sourcecode]
The tree walker
The tree walker needs to be passed an object of a class that implements the simpleFileVisitor.
Create a Path object refereing to the statring directory.
[sourcecode language=”java” toolbar=”false”]
Path startingDir = Paths.get("E:/personal/");
[/sourcecode]
Create a set of visit options
[sourcecode language=”java” toolbar=”false”]
EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
[/sourcecode]
Call the static method of the Files class
[sourcecode language=”java” toolbar=”false”]
Files.walkFileTree(startingDir, opts, Integer.MAX_VALUE, new FileVisitorImpl());
[/sourcecode]
Implement the SimpleFileVisitor.
[sourcecode language=”java” toolbar=”false”]</pre>
public class FileVisitorImpl extends SimpleFileVisitor{
public FileVisitResult visitFile(Path file, BasicFileAttributes attr){
System.out.format("FileName: %s", file);
return CONTINUE;
}
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
System.out.format("Directory: %s%n", dir);
return CONTINUE;
}
public FileVisitResult visitFileFailed(Path file, IOException exc){
System.err.println(exc);
return CONTINUE;
}
}
[/sourcecode]
Leave a Reply