Java中的Concat两个字节缓冲区
我怎样才能把两个便车换成一个便车 以下操作不起作用:Java中的Concat两个字节缓冲区,java,bytebuffer,Java,Bytebuffer,我怎样才能把两个便车换成一个便车 以下操作不起作用: ByteBuffer bb = ByteBuffer.allocate(100); ByteBuffer bb2 = ByteBuffer.allocate(200); bb.allocate(200).put(bb2); System.out.println(bb.array().length); bb的长度仍然是100请尝试以下代码: //store both ByteBuffer object as a
ByteBuffer bb = ByteBuffer.allocate(100);
ByteBuffer bb2 = ByteBuffer.allocate(200);
bb.allocate(200).put(bb2);
System.out.println(bb.array().length);
bb
的长度仍然是100
请尝试以下代码:
//store both ByteBuffer object as an array
byte[] array1 = ByteBuffer.allocate(100).array();
byte[] array2 = ByteBuffer.allocate(200).array();
//create a ByteBuffer which is big enough
ByteBuffer bigenough = ByteBuffer.allocate(array1.length + array2.length);
//put the two arrays in one ByteBuffer
ByteBuffer after1 = bigenough.put(array1, 0, array1.length);
ByteBuffer result = after1.put(array2, array1.length, array2.length);
//print the length of the combined array.
System.out.println(result.array().length);
差不多
bb = ByteBuffer.allocate(300).put(bb).put(bb2);
应该这样做:创建一个足够大的缓冲区来容纳两个缓冲区的内容,然后使用相对put方法来填充第一个和第二个缓冲区。(顺便说一下,
put
方法返回调用该方法的实例)我们将复制所有数据。请记住,这就是字符串连接代价高昂的原因
public static ByteBuffer concat(final ByteBuffer... buffers) {
final ByteBuffer combined = ByteBuffer.allocate(Arrays.stream(buffers).mapToInt(Buffer::remaining).sum());
Arrays.stream(buffers).forEach(b -> combined.put(b.duplicate()));
return combined;
}
你可以在这里使用这个方法 例如:
ByteBuffer concat() {
int length = 0;
for (ByteBuffer bb : buffers) {
bb.rewind();
length += bb.remaining();
}
ByteBuffer bbNew = ByteBuffer.allocateDirect((int) length);
// put all buffers from list
for (ByteBuffer bb : buffers) {
bb.rewind();
bbNew.put(bb);
}
bbNew.rewind();
return bbNew;
}
可能是因为第3行,即
bb.allocate(200).put(bb2)代码>,
bb.allocate(200)
正在返回一个新的字节缓冲区(请参阅)。这实际上并没有改变bb本身。因此,它仍然是第1行容量为100的bytebuffer。结果长度为200。我原以为自己会有300岁。我比安瑟进步了。但是你有没有考虑过仅仅是组合阵列本身?ByteBuffer是否必须使用?警告:位置
和限制
都将设置为容量
,如果您要进一步处理生成的ByteBuffer
,这可能不是您所期望或想要的。您需要调用.flip()
,以便通过添加.flip(),处理返回的ByteBuffer
的全部内容是的,flip()
或位置(0)
(我个人认为后者更具可读性)