Java snippet – get byte array of data actually written to ByteBuffer

By | August 26, 2013

Let’s say the buffer was allocated with bigger capacity than the written data. This code will get the written bytes


ByteBuffer buffer =  ByteBuffer.allocate(MAX);
buffer.put(...); // write data

ByteBuffer buf = (ByteBuffer) buffer.flip();
byte[] result = new byte[buf.limit()];
buf.get(result);

Leave a Reply

Your email address will not be published.