我尝试使用AsynchronousFileChannel实现复制文件。用于读写的AsynchronousFileChannel对象声明为
AsynchronousFileChannel asyncRead = AsynchronousFileChannel.open(sourcePath);
AsynchronousFileChannel asyncWrite = AsynchronousFileChannel.open(targetPath, StandardOpenOption.WRITE, StandardOpenOption.CREATE);读的CompletionHandler看起来像
CompletionHandler<Integer, ByteBuffer> handlerRead = new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer arg0, ByteBuffer arg1) {
System.out.println("finished read ...");
// question line
asyncWrite.write(ByteBuffer.wrap(arg1.array()), 0, null, handlerWrite);
}
@Override
public void failed(Throwable arg0, ByteBuffer arg1) {
System.out.println("failed to read ...");
}
};然后我开始读取文件
asyncRead.read(buffer, 0, buffer, handlerRead);问题是,在读取完成后,如果我写入文件(请参阅注释“问题行”以查看它的调用位置)。
// no output
asyncWrite.write(arg1, 0, null, handlerWrite);不会有任何内容被写出来。我必须再次包装缓冲器
// works fine
asyncWrite.write(ByteBuffer.wrap(arg1.array()), 0, null, handlerWrite);为了看到写出来的内容
我的问题是,为什么我必须使用ByteBuffer来包装另一个ByteBuffer的内容?
发布于 2014-11-10 02:50:04
为什么我必须使用ByteBuffer来包装另一个ByteBuffer的内容?
你没有,你应该换掉原来的ByteBuffer。通过调用wrap()获得了类似的效果,它将新包装的ByteBuffer的position设置为零。
https://stackoverflow.com/questions/26835948
复制相似问题