Concat在Java中使用两个ByteBuffers

问题描述 投票:8回答:5

如何将两个ByteBuffers连接到一个ByteBuffer?

以下不起作用:

    ByteBuffer bb = ByteBuffer.allocate(100);
    ByteBuffer bb2 = ByteBuffer.allocate(200);
    bb.allocate(200).put(bb2);
    System.out.println(bb.array().length);

bb的长度仍然是100

java bytebuffer
5个回答
9
投票

就像是

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

应该做的工作:创建一个足够大的缓冲区来保存两个缓冲区的内容,然后使用相对的put方法用第一个和第二个缓冲区填充它。 (顺便说一句,put方法返回调用方法的实例)


2
投票

我们将复制所有数据。请记住,这就是为什么字符串连接很昂贵!

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;
}

0
投票

你可以在这里使用这个方法

https://github.com/ata4/ioutils/blob/047e401d73c866317af2e12f7803b3ee43eec80a/src/main/java/info/ata4/io/buffer/ByteBufferUtils.java#L289

例如:

  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;
}

0
投票

可能是因为在line3即bb.allocate(200).put(bb2);

bb.allocate(200)正在返回一个新的字节缓冲区(参见https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#allocate(int))。这实际上并没有改变bb本身。所以它仍然是line1的容量100的字节缓冲区。


-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);
© www.soinside.com 2019 - 2024. All rights reserved.