Java NIO: reading variable-sized blocks

buffer, java, nio

Solution

if `stream` is a `SocketChannel` and `buffer` is a `ByteBuffer`, you can do the following:

//assuming buffer is a ByteBuffer
buffer.position(0);
buffer.limit(1);
while (buffer.hasRemaining()) { 
   stream.read(buffer);
}
buffer.rewind();

//get the byte and cast it into the range 0-255
int length = buffer.get() & 0xFF;
buffer.clear();
buffer.limit(length);
while (buffer.hasRemaining()) { 
   stream.read(buffer);
}
buffer.rewind();
//the buffer is now ready for reading the data from

Problem

I would like to read a string from a TCP stream that is given with a byte length followed by the actual data. In Python, I would do ``` length = ord(stream.read(1)) data = stream.read(length) ``` How do I do the same in Java NIO? What I have is a buffer (of capacity 257) ``` stream.read(buffer); // cannot specify a size here int length = buffer.get(); byte[] data = new byte[length]; buffer.get(data); ``` Unfortunately, this doesn't work: the get() calls read past the data in the buffer :-( I probably need some combination of flip, rewind, reset, etc., but I can't figure it out.

Original source