我正在与AsynchronousFileChannel一起阅读数据。对于读取数据,我发现了两个读取方法,如下所示:
//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)正如下面指定的java文档一样,没有关于将CompletionHandler用作函数的第三个参数的信息:
从给定的文件位置开始,将一系列字节从这个通道读入给定的缓冲区。 此方法从给定的文件位置开始,从该通道开始将一系列字节读入给定的缓冲区。读取的结果是读取的字节数,如果在尝试读取时给定的位置大于或等于文件的大小,则为-1。 该方法的工作方式与AsynchronousByteChannel.read(ByteBuffer,Object,CompletionHandler)方法相同,只是从给定的文件位置开始读取字节。如果在尝试读取时,给定的文件位置大于文件的大小,则不会读取任何字节。
有人能让我知道第三个参数,以及CompletionHandler的任何工作示例吗?为什么我们需要CompletionHandler ?它的用法是什么?
发布于 2016-12-12 11:37:09
下面是我搜索的示例,并使其工作如下:
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();
}以下是处理细节:
读取操作完成后,将调用CompletionHandler的CompletionHandler()方法。将参数传递给completed()方法时,将传递一个Integer,说明读取了多少字节,以及传递给read()方法的“附件”。“附件”是read()方法的第三个参数。在这种情况下,数据也被读入到ByteBuffer中。
如果读取操作失败,则将调用CompletionHandler的failed()方法。
https://stackoverflow.com/questions/41098651
复制相似问题