Convert ByteBuffer to byte array java [duplicate]

眉间皱痕 提交于 2019-12-09 08:02:34

问题


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.


回答1:


ByteBuffer exposes 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 buf = ...
byte[] arr = new byte[buf.remaining()];
buf.get(arr);



回答2:


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

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.



来源:https://stackoverflow.com/questions/28744096/convert-bytebuffer-to-byte-array-java

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