Java Utililty Methods ByteBuffer Compact

List of utility methods to do ByteBuffer Compact

Description

The list of methods to do ByteBuffer Compact are organized into topic(s).

Method

ByteBuffercompact(ByteBuffer buffer)
compact
return buffer.compact();
voidcompact(ByteBuffer buffer)
compact
if (buffer.hasRemaining()) {
    if (buffer.position() == 0) {
        buffer.position(buffer.remaining());
        buffer.limit(buffer.capacity());
    } else
        buffer.compact();
} else
    buffer.clear();
...
booleancompact(ByteBuffer buffer)
Compact the buffer
if (buffer.position() == 0)
    return false;
boolean full = buffer.limit() == buffer.capacity();
buffer.compact().flip();
return full && buffer.limit() < buffer.capacity();
ByteBuffer[]compact(ByteBuffer[] buffers)
Compacts an array of byte buffers, retaining only the buffers that have remaining data.
for (int i = 0; i < buffers.length; i++) {
    if (buffers[i].remaining() > 0) {
        if (i == 0)
            return buffers;
        ByteBuffer[] newBuffers = new ByteBuffer[buffers.length - i];
        System.arraycopy(buffers, i, newBuffers, 0, buffers.length - i);
        return newBuffers;
return null;
byte[]toCompactArray(ByteBuffer src)
Return an appropriately sized byte array filled with the contents of src.
if (src.hasArray() && src.limit() >= src.capacity()) { 
    return src.array();
assertReadyForFreshRead(src);
byte[] dest = new byte[src.limit()];
src.get(dest); 
assert (src.position() == src.limit()); 
src.rewind(); 
...