Determine number of Bytes in ByteBuffer
Solution 1
After you've written to the ByteBuffer, the number of bytes you've written can be found with the position()
method.
If you then flip()
the buffer, the number of bytes in the buffer can be found with the limit()
or remaining()
methods.
If you then read some of the buffer, the number of bytes remaining can be found with the remaining()
method.
Solution 2
DatagramChannel channel = DatagramChannel.open();
ByteBuffer bb = ByteBuffer.allocate(5+size);
channel.receive(bb);
bb.flip();
// actual length of received packet
int len = bb.remaining();
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on December 16, 2020Comments
-
Admin over 3 years
I have a
ByteBuffer
that can hold a maximum of (4 +size
)bytes
(that is, an integer followed bysize
characters). However, the number of characters written to theByteBuffer
, may be smaller thansize
.So I was wondering, is there anyway to determine how many characters were written to the
ByteBuffer
and not just the total size of it?limit
,position
and such don't SEEM to be what I am after.Thanks for your help!