0

为什么这不起作用?

如果您检查 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));
}
4

2 回答 2

5

问题是put(byte)增加了当前位置,所以当它试图读取bb将结果放入tt时,它是从缓冲区的末尾读取的。

做你想做的事,你想要这样的东西:

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 直接转换为一个字节。

于 2013-10-23T23:37:35.207 回答
-2

你有没有试过这个:

bb.put((new Byte(""+i)).byteValue());
于 2013-10-23T23:42:49.707 回答