How do I getInt from a ByteBuffer with only 1 remaining byte (Java NIO)

I am new to Java NIO and am unsure how to do things nio-ishly.

Assume I have read some data from a socket into a ByteBuffer and consumed all bytes but one, using the get methods of ByteBuffer. I know the next thing will be four bytes with an integer in binary format, so I want to use getInt(), but only the first byte of the int is in the buffer.

The natural thing to me is to fill up the buffer with some more bytes from the connection and then continue. If I understand correctly, I could achieve this with


and then read more bytes.

Since there is no method with that behavior, but there is the flip() method, I wonder if my thinking is wrong. Are there better ways to do this?

This situation will naturally occur e.g. if the connection delivers a stream of length + data messages.


// wrong: buf.position(buf.limit()); 
// no need to: buf.limit(buf.capacity()); 

Please do not change the position. Position after compact() is pointing to the first byte after the un-getted part of the buffer – exactly where you want it.

Setting limit to capacity is redundant: compact() already does it for you.

Leave a Reply

Your email address will not be published. Required fields are marked *