简体   繁体   English

确定ByteBuffer中的字节数

[英]Determine number of Bytes in ByteBuffer

I have a ByteBuffer that can hold a maximum of (4 + size ) bytes (that is, an integer followed by size characters). 我有一个ByteBuffer ,可以容纳最多(4 + sizebytes (即一个整数后跟size字符)。 However, the number of characters written to the ByteBuffer , may be smaller than size . 但是,写入ByteBuffer的字符数可能小于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? 所以我想知道,无论如何要确定有多少字符写入ByteBuffer而不仅仅是它的总大小? limit , position and such don't SEEM to be what I am after. limitposition等不要SEEM成为我所追求的。

Thanks for your help! 谢谢你的帮助!

After you've written to the ByteBuffer, the number of bytes you've written can be found with the position() method. 在写入ByteBuffer之后,可以使用position()方法找到您编写的字节数。

If you then flip() the buffer, the number of bytes in the buffer can be found with the limit() or remaining() methods. 如果然后flip()缓冲区,可以使用limit()remaining()方法找到缓冲区中的字节数。

If you then read some of the buffer, the number of bytes remaining can be found with the remaining() method. 如果您随后读取了一些缓冲区,则可以使用remaining()方法找到剩余的字节数。

DatagramChannel channel = DatagramChannel.open();
ByteBuffer bb = ByteBuffer.allocate(5+size);
channel.receive(bb);
bb.flip();
// actual length of received packet
int len = bb.remaining();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM