Hot Posts

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
Path dir = Paths.get("E:/Development/CodeSource/java7/test");
  • Create a new watch service
WatchService watcher = FileSystems.getDefault().newWatchService();
WatchService watcher = dir.getFileSystem().newWatchService();
  • Register directory with the watcher(mutiple directories can be registered)
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
  • Get the watch key (the application waits here until an event occurs)
WatchKey watckKey = watcher.take();
  • When an event occurs we poll it and then treat it
for (WatchEvent<?> event: key.pollEvents()) {}
  • To get the type of event
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {}

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.

Path startingDir = Paths.get("E:/personal/");

Create a set of visit options

EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

Call the static method of the Files class

Files.walkFileTree(startingDir, opts, Integer.MAX_VALUE, new FileVisitorImpl());

Implement the SimpleFileVisitor.

</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;
 }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: