2013-02-14 128 views
1

我有一个ByteBuffer包含1024个字节。Java字节缓冲区覆盖字节

我需要在关键时间以某个偏移量在缓冲区中覆盖一个短路。

我知道ByteBuffer类有putShort(),但这不会覆盖数据,只是将其添加进来,导致缓冲区溢出。

我猜测没有一个使用ByteBuffer这样做的直接方法,有人可能会建议一种方法来做到这一点吗?

感谢

感谢大家的回答,似乎它可能我只是用putShort的错误版本()来完成。我想这就是当你盯着同一段代码六个小时时会发生什么。

再次感谢

+5

'ByteBuffer'有两个'putShort'方法:['putShort(短值)'](HTTP:// docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#putShort(short))和['putShort(int index,short value)'](http://docs.oracle.com /javase/7/docs/api/java/nio/ByteBuffer.html#putShort(int,%20short))。你确定你使用的是正确的吗? – 2013-02-14 16:51:56

+0

我完全使用了错误的!谢谢马克,问题解决了:) – Tony 2013-02-14 17:01:20

回答

3

不能重现该问题,一切似乎都OK

ByteBuffer bb = ByteBuffer.allocate(20); 
    bb.putShort(10, (short)0xffff); 
    System.out.println(Arrays.toString(bb.array())); 

打印

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0] 
1

对于你的特殊情况下,你可以直接在backing array使用array()方法修改。

然后,只需在适当的索引插入你的两个字节:

if(myBuffer.hasArray()) { 
    byte[] array = myBuffer.array(); 
    array[index] = (byte) (myShort & 0xff); 
    array[index + 1] = (byte) ((myShort >> 8) & 0xff); 
}