[英]Java AsynchronousFileChannel and ByteBuffer
我嘗試使用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的內容是什么原因?
我必須使用ByteBuffer來包裝另一個ByteBuffer的內容是什么原因?
你沒有。 你應該翻轉原來的ByteBuffer
。 你通過調用wrap()
獲得類似的效果,它將新包裝的ByteBuffer
的position
設置為零。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.