Determine number of Bytes in ByteBuffer

48,462

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();
Share:
48,462
Admin
Author by

Admin

Updated on December 16, 2020

Comments

  • Admin
    Admin over 3 years

    I have a ByteBuffer that can hold a maximum of (4 + size) bytes (that is, an integer followed by size characters). However, the number of characters written to the ByteBuffer , may be smaller than size.

    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!