Java Reference
In-Depth Information
to see which are ready for reading or writing. The classes to support this are in the
java.nio.channels package and include SelectableChannel and Selector .
These nonblocking multiplexed techniques can be extremely useful when writing
advanced applications that require high scalability, but a full discussion is outside
the scope of this topic.
g
d O
e
Watch Services and Directory Searching
The last class of asynchronous services we will consider are those that watch a direc‐
tory, or visit a directory (or a tree). The watch services operate by observing every‐
thing that happens within 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 accord‐
ing 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:
Search WWH ::




Custom Search