ByteBuffer compact() method in Java with Examples
The compact() method of java.nio.ByteBuffer class is used to compact the given buffer.
The bytes between the buffer’s current position and its limit, if any, are copied to the beginning of the buffer. That is, the byte at index p = position() is copied to index zero, the byte at index p + 1 is copied to index one, and so forth until the byte at index limit() – 1 is copied to index n = limit() – 1 – p. The buffer’s position is then set to n+1 and its limit is set to its capacity. The mark, if defined, is discarded.
The buffer’s position is set to the number of bytes copied, rather than to zero, so that an invocation of this method can be followed immediately by an invocation of another relative put method.
Invoke this method after writing data from a buffer in case the write was incomplete.
public abstract ByteBuffer compact()
Return Value: This method returns the new ByteBuffer with the same content as that of this buffer.
Exception: This method throws the ReadOnlyBufferException, If this buffer is read-only.
Below program illustrates the compact() method:
Original ByteBuffer: [20, 30, 40, 0, 0, 0, 0] Position: 3 limit: 7 Compacted ByteBuffer: [0, 0, 0, 0, 0, 0, 0] Position: 4 limit: 7 Updated Compacted ByteBuffer: [0, 0, 0, 0, 50, 0, 0] Position: 5 limit: 7
ReadOnlyBuffer ByteBuffer: 20, 30, 40, 0, 0, Position: 0 limit: 5 Trying to compact the ReadOnlyBuffer bb1 Exception throws java.nio.ReadOnlyBufferException