Java Reference
In-Depth Information
// An inner class to handle completion of the asynchronous read operation
private static class ReadHandler
implements CompletionHandler<Integer, Attachment> {
@Override
public void completed(Integer result, Attachment attach) {
System.out.format("%s bytes read from %s%n",
result, attach.path);
System.out.format("Read data is:%n");
byte[] byteData = attach.buffer.array();
Charset cs = Charset.forName("UTF-8");
String data = new String(byteData, cs);
System.out.println(data);
try {
// Close the channel
attach.asyncChannel.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void failed(Throwable e, Attachment attach) {
System.out.format("Read operation on %s file failed." +
"The error is: %s%n",
attach.path, e.getMessage());
try {
// Close the channel
attach.asyncChannel.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
}
public static void main(String[] args) {
Path path = Paths.get("rainbow.txt");
try {
// Get an async channel
AsynchronousFileChannel afc =
AsynchronousFileChannel.open(path, READ);
// Get a completion handler
ReadHandler handler = new ReadHandler();
Search WWH ::




Custom Search