Java Reference
In-Depth Information
catch (InterruptedException e) {
e.printStackTrace();
}
}
// I/O is complete
try {
int writtenBytes = result.get();
System.out.format("%s bytes written to %s%n",
writtenBytes, path.toAbsolutePath());
}
catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Sleeping for 2 seconds...
228 bytes written to C:\book\javabook\rainbow.txt
Listing 10-23 demonstrates how to use a CompletionHandler object to handle the results of an asynchronous
read from a file. The program reads and prints the contents a rainbow.txt file in the default directory. To read the
contents of a different file, change the path of the file in the main() method. You may get a different output.
Listing 10-23. Using a CompletionHandler to Handle the Result of an Asynchronous File Read
// AsyncFileRead.java
package com.jdojo.nio2;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.channels.CompletionHandler;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.charset.Charset;
import static java.nio.file.StandardOpenOption.READ;
public class AsyncFileRead {
// Used as an attachment to the CompletionHandler
private static class Attachment {
public Path path;
public ByteBuffer buffer;
public AsynchronousFileChannel asyncChannel;
}
Search WWH ::




Custom Search