kal*_*kal 84 java arrays nio bytebuffer bytearray
这是从ByteBuffer获取字节的推荐方法
ByteBuffer bb =..
byte[] b = new byte[bb.remaining()]
bb.get(b, 0, b.length);
Run Code Online (Sandbox Code Playgroud)
Jas*_*n S 100
取决于你想做什么.
如果你想要的是检索剩余的字节(在位置和限制之间),那么你所拥有的将是有效的.你也可以这样做:
ByteBuffer bb =..
byte[] b = new byte[bb.remaining()]
bb.get(b);
Run Code Online (Sandbox Code Playgroud)
这相当于ByteBuffer javadocs.
R4z*_*rax 18
请注意,bb.array()不支持字节缓冲区位置,如果您正在处理的bytebuffer是某个其他缓冲区的片段,则可能更糟糕.
即
byte[] test = "Hello World".getBytes("Latin1");
ByteBuffer b1 = ByteBuffer.wrap(test);
byte[] hello = new byte[6];
b1.get(hello); // "Hello "
ByteBuffer b2 = b1.slice(); // position = 0, string = "World"
byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".
byte[] world = new byte[5];
b2.get(world); // world = "World"
Run Code Online (Sandbox Code Playgroud)
这可能不是你打算做的.
如果你真的不想复制字节数组,可以使用字节缓冲区的arrayOffset()+ remaining(),但这只适用于应用程序支持索引+字节缓冲区长度的情况需要.
final ByteBuffer buffer;
if (buffer.hasArray()) {
final byte[] array = buffer.array();
final int arrayOffset = buffer.arrayOffset();
return Arrays.copyOfRange(array, arrayOffset + buffer.position(),
arrayOffset + buffer.limit());
}
// do something else
Run Code Online (Sandbox Code Playgroud)
就如此容易
private static byte[] getByteArrayFromByteBuffer(ByteBuffer byteBuffer) {
byte[] bytesArray = new byte[byteBuffer.remaining()];
byteBuffer.get(bytesArray, 0, bytesArray.length);
return bytesArray;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
124433 次 |
| 最近记录: |