Java Magazine, July/August 2016
ORACLE COM JAVAMAGAZINE JULY AUGUST 2016 55 new to java Watch Services and Directory Searching The last class of asynchronous services we will consider watch a directory or visit a directory or a tree The watch services operate by observing everything that happens in a directory for example the creation or modification of files try WatchService watcher FileSystems getDefault newWatchService Path dir FileSystems getDefault getPath home ben WatchKey key dir register watcher StandardWatchEventKinds ENTRY_ CREATE StandardWatchEventKinds ENTRY_ MODIFY StandardWatchEventKinds ENTRY_ DELETE while shutdown key watcher take for WatchEvent event key pollEvents Object o event context if o instanceof Path System out println Path altered o key reset By contrast the directory streams provide a view into all files currently in a single directory For example to list all the Java source files and their size in bytes we can use code like try DirectoryStream Path stream Files newDirectoryStream Paths get opt projects java for Path p stream System out println p Files size p One drawback of this API is that this will only return elements that match according to glob syntax which is sometimes insufficiently flexible We can go further by using the new Files find and Files walk methods to address each element obtained by a recursive walk through the directory final Pattern isJava Pattern compile java final Path homeDir Paths get Users ben projects Files find homeDir 255 p attrs isJava matcher p toString find forEach q System out println q normalize It is possible to go even further and construct advanced solutions based on the FileVisitor interface in java nio file but that requires the developer to implement all four methods on the interface rather than just using a single lambda expression as done here In sum you can see that the NIO 2 library provides a lot of useful functionality and saves you a lot of code If youre still working with pre Java 7 file handling youre doing far more work than necessary article This article was adapted with permission from Java in a Nutshell by Benjamin Evans and David Flanagan Benjamin Evans is the cofounder of jClarity a Java Champion and Rock Star and a frequent contributor to Java Magazine David Flanagan is a software engineer at Mozilla best known for his master work JavaScript the Definitive Guide OReilly 2011
You must have JavaScript enabled to view digital editions.