Determine number of Bytes in ByteBuffer

user2268507 picture user2268507 · Jun 2, 2013 · Viewed 42.3k times · Source

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!

Answer

Andy Thomas picture Andy Thomas · Jun 2, 2013

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.