~/ learn/ comp-348/ cards/ Buffers: four numbers and one invariant
1 of 5

Fill a buffer from a channel, flip it, drain it

Fill a buffer from a channel, flip it, drain it

Answer

ByteBuffer buf = ByteBuffer.allocate(10); channel.read(buf); buf.flip(); while (buf.hasRemaining()) System.out.print((char) buf.get());

read() writes at position and advances it, so after the read position sits past the data. flip() sets limit to that point and position back to 0, which is what makes hasRemaining() true for exactly the bytes that arrived. Drop the flip() and the loop body never runs.

Harold 4e ch11 §Buffers

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/c1522018-69e3-4cd0-84fd-8dbd48f458e5/flashcard utf-8 LF