Java Reference
In-Depth Information
public class AsyncFileWrite {
// Used as an attachment to the CompletionHandler
private static class Attachment {
public Path path;
public ByteBuffer buffer;
public AsynchronousFileChannel asyncChannel;
}
// An inner class to handle completion of the asynchronous write operation
private static class WriteHandler
implements CompletionHandler<Integer, Attachment> {
@Override
public void completed(Integer result, Attachment attach) {
System.out.format("%s bytes written to %s%n",
result, attach.path.toAbsolutePath());
try {
// Close the channel
attach.asyncChannel.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void failed(Throwable e, Attachment attach) {
System.out.format("Write 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, WRITE, CREATE);
// Get a completion handler
WriteHandler handler = new WriteHandler();
Search WWH ::




Custom Search