How to get getInt from ByteBuffer with only one byte left (Java NIO)

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

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

It is natural for me to fill the buffer with a few more bytes from the connection, and then continue. If I understood correctly, I could achieve this with

 buf.compact(); buf.position(buf.limit()); buf.limit(buf.capacity()); 

and then read more bytes.

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

This situation will naturally happen, for example. if the connection provides a stream of length + data messages.

+5
source share
1 answer
 buf.compact(); // wrong: buf.position(buf.limit()); // no need to: buf.limit(buf.capacity()); 

Please do not change the position. The position after compact() points to the first byte after the unpainted portion of the buffer — exactly where you want it.

Setting a capacity limit is redundant: compact() already does this for you.

+2
source

Source: https://habr.com/ru/post/1242396/


All Articles