Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat two ByteBuffers in Java

How can I concat two ByteBuffers to one ByteBuffer?

The following doesn't work:

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

The length of bb is still 100.

like image 870
mcfly soft Avatar asked Apr 22 '14 12:04

mcfly soft


2 Answers

Something like

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

should do the job: Create a buffer that is large enough to hold the contents of both buffers, and then use the relative put-methods to fill it with the first and the second buffer. (The put method returns the instance that the method was called on, by the way)

like image 113
Marco13 Avatar answered Nov 09 '22 10:11

Marco13


We'll be copying all data. Remember that this is why string concatenation is expensive!

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;
}
like image 2
TJR Avatar answered Nov 09 '22 10:11

TJR