将ByteBuffer转换为字节数组java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28744096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:43:21  来源:igfitidea点击:

Convert ByteBuffer to byte array java

javaarraysbytearraybytebuffer

提问by Powisss

Does anyone know how to convert ByteBuffer to byte[] array? I need to get byte array from my ByteBuffer. When I run bytebuffer.hasArrray()it returns no. Every question I looked so far is converting byte array to byteBuffer, but I need it other way around. Thank you.

有谁知道如何将 ByteBuffer 转换为 byte[] 数组?我需要从我的ByteBuffer. 当我运行时,bytebuffer.hasArrray()它返回 no。到目前为止,我看到的每个问题都是将字节数组转换为 byteBuffer,但我需要其他方式。谢谢你。

采纳答案by nomis

ByteBufferexposes the bulk get(byte[])method which transfers bytes from the buffer into the array. You'll need to instantiate an array of length equal to the number of remaining bytes in the buffer.

ByteBuffer公开get(byte[])将字节从缓冲区传输到数组的批量方法。您需要实例化一个长度等于缓冲区中剩余字节数的数组。

ByteBuffer buf = ...
byte[] arr = new byte[buf.remaining()];
buf.get(arr);

回答by Stephen C

If hasArray()reports falsethen, calling array()will throw an exception.

如果hasArray()报告false然后,调用array()将抛出异常。

In that case, the only way to get the data in a byte[]is to allocate a byte[]and copy the bytes to the byte[]using get(byte)or similar.

在这种情况下,获取 a 中数据的唯一方法byte[]是分配 abyte[]并将字节复制到byte[]usingget(byte)或类似的。