问题
I am working with the AsynchronousFileChannel for reading on the data. For reading the data, i found two read methods as follows:
//1.
Future<Integer> java.nio.channels.AsynchronousFileChannel.read(ByteBuffer dst, long position);
//2.
void java.nio.channels.AsynchronousFileChannel.read(ByteBuffer dst, long position, A attachment, CompletionHandler<Integer, ? super A> handler)
As the java documentation specified as below, there is no information about the CompletionHandler being used as the third parameter of the function:
Reads a sequence of bytes from this channel into the given buffer, starting at the given file position.
This method initiates the reading of a sequence of bytes from this channel into the given buffer, starting at the given file position. The result of the read is the number of bytes read or -1 if the given position is greater than or equal to the file's size at the time that the read is attempted.
This method works in the same manner as the AsynchronousByteChannel.read(ByteBuffer, Object, CompletionHandler) method, except that bytes are read starting at the given file position. If the given file position is greater than the file's size at the time that the read is attempted then no bytes are read.
Can anybody let me know about the third parameter, and any working example for CompletionHandler? Why do we need to CompletionHandler and what's its usage?
回答1:
Here is the example which I searched and got it working as follows:
try(AsynchronousFileChannel asyncfileChannel = AsynchronousFileChannel.open(Paths.get("/Users/***/Documents/server_pull/system_health_12_9_TestServer.json"), StandardOpenOption.READ)){
ByteBuffer buffer = ByteBuffer.allocate(1024);
ByteBuffer attachment = ByteBuffer.allocate(1024);
asyncfileChannel.read(buffer, 0, attachment, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
System.out.println("result = " + result);
attachment.flip();
byte[] data = new byte[attachment.limit()];
attachment.get(data);
System.out.println(new String(data));
attachment.clear();
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
}
});
}catch(Exception e){
e.printStackTrace();
}
And below is the processing details:
Once the read operation finishes, the CompletionHandler's completed() method will be called. As parameters to the completed() method are passed an Integer telling how many bytes were read, and the "attachment" which was passed to the read() method. The "attachment" is the third parameter to the read() method. In this case it was the ByteBuffer into which the data is also read.
If the read operation fails, the failed() method of the CompletionHandler will get called instead.
来源:https://stackoverflow.com/questions/41098651/what-is-the-use-of-completionhandler-in-asynchronousfilechannel-for-reading-data