Streaming bytes, encoding and buffer state
Definition:
A ByteBuffer tracks position, limit and capacity for bounded byte transfer.
Explanation:
A buffer separates storage capacity, position and limit.
Illustration image:
Example:
var buffer = java.nio.ByteBuffer.allocate(8);
buffer.put((byte)65);
buffer.flip();
System.out.println((char) buffer.get());Expected behavior. Prints A. After flip, the readable limit is the prior write position.
Internal working:
For a channel read into a ByteBuffer, flip prepares produced bytes for consumption; compact preserves unread bytes before additional reads. A network read can return partial protocol data. Decode chunks with a CharsetDecoder when multibyte sequences can straddle chunks. Close streams returned by Files.lines and similar operations.
Interview questions:
What does flip do after a channel read?
It makes the old position the reading limit and resets the position to zero.