Determine number of Bytes in ByteBuffer

不打扰是莪最后的温柔 提交于 2019-12-21 03:33:28

问题


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


来源:https://stackoverflow.com/questions/16879078/determine-number-of-bytes-in-bytebuffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!