首页 > 其他 > 详细

Gets byte array from a ByteBuffer in java

时间:2014-03-11 11:00:37      阅读:441      评论:0      收藏:0      [点我收藏+]

Is this the recommended way to get the bytes from the ByteBuffer

ByteBuffer bb =..byte[] b =newbyte[bb.remaining()]
bb.get(b,0, b.length);
share|improve this question
  add comment

Depends what you want to do.

If what you want is to retrieve the bytes that are remaining (between position and limit), then what you have will work. You could also just do:

ByteBuffer bb =..byte[] b =newbyte[bb.remaining()]
bb.get(b);

which is equivalent as per the ByteBuffer javadocs.

share|improve this answer
 
1  
Correct. And note that bb.capacity() might equal bb.remaining() even when the backing array is longer, so you must not use their equality as a test of when bb.array() is correct. SeeByteBuffer.slice(). –  cdunn2001 Sep 26 ‘12 at 0:01
add comment
bubuko.com,布布扣bubuko.com,布布扣

bb.array() will return the byte array that backs the buffer.

share|improve this answer
 
5  
...if there is one. "Invoke the hasArray method before invoking this method in order to ensure that this buffer has an accessible backing array." –  Michael Myers? Mar 24 ‘09 at 21:25
2  
Also it won‘t work if the byte array is read only, as that would bypass the read-only property & violate the ByteBuffer‘s contract. –  Jason S Mar 24 ‘09 at 21:30
1  
Also the backing array may be bigger than actual limit. So you may get something wrong -- see Rasmus Fuglsang‘s answer for example. –  Piotr Findeisen Nov 27 at 9:41 
add comment

Note that the bb.array() doesn‘t honor the byte-buffers position, and might be even worse if the bytebuffer you are working on is a slice of some other buffer.

I.e.

byte[] test ="Hello World".getBytes("Latin1");ByteBuffer b1 =ByteBuffer.wrap(test);byte[] hello =newbyte[6];
b1.get(hello);ByteBuffer b2 = b1.slice();// position = 0, string = "World"byte[] tooLong = b2.array();// Will NOT be "World", but will be "Hello World".byte[] world =newbyte[5];
b2.get(world);// world = "World"

Which might not be what you intend to do.

If you really do not want to copy the byte-array, a work-around could be to use the byte-buffer‘s arrayOffset() + remaining(), but this only works if the application supports index+length of the byte-buffers it needs.

share|improve this answer
  add comment

This is a simple way to get a byte[], but part of the point of using a ByteBuffer is avoiding having to create a byte[]. Perhaps you can get whatever you wanted to get from the byte[] directly from the ByteBuffer.

share|improve this answer
 
   
But often you‘ll need to call something (not in your own code) that takes a byte[], so converting isn‘t optional. –  James Moore Mar 16 ‘11 at 14:55

Gets byte array from a ByteBuffer in java,布布扣,bubuko.com

Gets byte array from a ByteBuffer in java

原文:http://www.cnblogs.com/beautiful-scenery/p/3590021.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!