Determine number of Bytes in ByteBuffer

2020-06-07 06:57发布

问题:

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!

回答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.



回答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();