java – 如何从ByteBuffer获取used byte []
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 如何从ByteBuffer获取used byte [],小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1419字,纯文字阅读大概需要3分钟。
内容图文
![java – 如何从ByteBuffer获取used byte []](/upload/InfoBanner/zyjiaocheng/795/de7b21eb5e2d457f9913c10b0e794368.jpg)
java.nio.ByteBuffer类有一个ByteBuffer.array()方法,但是这会返回一个数组,该数组是缓冲区容量的大小,而不是已用容量.因此,我遇到了很多问题.
我注意到使用ByteBuffer.remaining()给了我缓冲区当前正在使用的字节数,所以基本上我正在寻找的是获取只使用字节的byte []的方法. (即,ByteBuffer.remaining()中显示的字节.
我尝试了一些不同的东西,但我似乎失败了,唯一的解决方法是我能想到它创建另一个ByteBuffer并分配剩余缓冲区的大小,然后写入(x)字节.
解决方法:
从读取Javadocs开始,我认为只剩下当前位置和限制之间的字节数.
remaining()
Returns the number of elements between the current position and the limit.
此外:
A buffer’s capacity is the number of elements it contains. The capacity of a buffer is never negative and never changes.
A buffer’s limit is the index of the first element that should not be read or written. A buffer’s limit is never negative and is never greater than its capacity.
A buffer’s position is the index of the next element to be read or written. A buffer’s position is never negative and is never greater than its limit.
所以考虑到这一点:
static byte[] getByteArray(ByteBuffer bb) {
byte[] ba = new byte[bb.limit()];
bb.get(ba);
return ba;
}
这使用了ByteBuffer的get(byte [] dst)方法
public ByteBuffer get(byte[] dst)
Relative bulk get method.
This method transfers bytes from this buffer into the given destination array. An invocation of this method of the form src.get(a) behaves in exactly the same way as the invocation06001
内容总结
以上是互联网集市为您收集整理的java – 如何从ByteBuffer获取used byte []全部内容,希望文章能够帮你解决java – 如何从ByteBuffer获取used byte []所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。