在Java中连接两个字节缓冲区

10
我如何将两个ByteBuffer连接成一个ByteBuffer?
以下方法不可行:
    ByteBuffer bb = ByteBuffer.allocate(100);
    ByteBuffer bb2 = ByteBuffer.allocate(200);
    bb.allocate(200).put(bb2);
    System.out.println(bb.array().length);
< p > bb 的长度仍然是 100

5个回答

12

类似于某物

bb = ByteBuffer.allocate(300).put(bb).put(bb2);

应该这样做:创建一个足够大的缓冲区来容纳两个缓冲区的内容,然后使用相对的put方法来填充第一个和第二个缓冲区的内容。顺便提一下,put方法会返回调用该方法的实例。


7
警告:positionlimit 都将被设置为 capacity,这很可能不是您希望的结果,如果您打算进一步处理返回的 ByteBuffer,您需要调用 .flip() 来添加.flip();以便能够处理整个返回的 ByteBuffer 内容。 - user177800
是的,flip()position(0)(我个人认为后者更易读) - Marco13

3
我们将复制所有的数据。请记住这就是为什么字符串连接操作很耗费资源的原因!
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;
}

似乎可以工作(并且比其他提出的解决方案更干净),除非您可能想在结尾之前添加:combined.rewind(); - Jesse Glick
我同意,这很模糊。光标应该在前面还是后面?也许方法名应该表明这一点。 - TJR

0

0

-1
请尝试以下代码:
//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);

结果的长度为200。我预期应该是300。 - mcfly soft
我改进了答案。但是你考虑过将数组合并吗?ByteBuffer是否必须使用? - Roelof van den Berg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接