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