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