为什么这不起作用?
如果检查tt的后备数组,则所有值均为0,而bb为1-100的序列 为什么system.out最后不相同?
ByteBuffer bb = ByteBuffer.allocateDirect(100);
for(int i =0;i< 100; i++) {
bb.put(new Byte(""+i));
}
ByteBuffer tt = ByteBuffer.allocateDirect(100);
tt.put(bb);
for(int i =0;i< 100; i++) {
System.out.println("BACKED bb" + bb.get(i));
System.out.println("BACKED tt" + tt.get(i));
}
答案 0 :(得分:4)
问题是put(byte)
会增加当前位置,因此当它尝试读取bb
以将结果放入tt
时,它会从缓冲区的末尾读取。 / p>
要做你想做的事,你需要像:
ByteBuffer bb = ByteBuffer.allocateDirect(100);
for(int i =0;i< 100; i++) {
bb.put((byte)i);
}
ByteBuffer tt = ByteBuffer.allocateDirect(100);
// reset the position so that we can copy it to the new ByteBuffer.
// Could also call bb.rewind() here.
bb.position(0);
tt.put(bb);
for(int i =0;i< 100; i++) {
System.out.println("BACKED bb" + bb.get(i));
System.out.println("BACKED tt" + tt.get(i));
}
顺便说一下,我稍微改变了创建,没有必要创建一个字符串来获取字节值,只需将int直接转换为一个字节。
答案 1 :(得分:-2)
你试过这个:
bb.put((new Byte(""+i)).byteValue());