developer tip

Java의 ByteBuffer에서 바이트 배열을 가져옵니다.

optionbox 2020. 9. 22. 08:04
반응형

Java의 ByteBuffer에서 바이트 배열을 가져옵니다.


이것이 ByteBuffer에서 바이트를 가져 오는 데 권장되는 방법입니까?

ByteBuffer bb =..

byte[] b = new byte[bb.remaining()]
bb.get(b, 0, b.length);

하고 싶은 일에 따라 다릅니다.

원하는 것이 (위치와 한계 사이) 남아있는 바이트를 검색하는 것이라면 가지고있는 것이 작동합니다. 다음과 같이 할 수도 있습니다.

ByteBuffer bb =..

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

이는 ByteBuffer javadocs에 따라 동일 합니다.


bb.array ()는 바이트 버퍼 위치를 따르지 않으며 작업중인 바이트 버퍼가 다른 버퍼의 슬라이스 인 경우 더 나쁠 수 있습니다.

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"

당신이하려는 것이 아닐 수도 있습니다.

실제로 바이트 배열을 복사하지 않으려면 해결 방법은 바이트 버퍼의 arrayOffset () + left ()를 사용하는 것입니다. 그러나 이것은 응용 프로그램이 바이트 버퍼의 index + length를 지원하는 경우에만 작동합니다. 필요합니다.


저것과 같이 쉬운

  private static byte[] getByteArrayFromByteBuffer(ByteBuffer byteBuffer) {
    byte[] bytesArray = new byte[byteBuffer.remaining()];
    byteBuffer.get(bytesArray, 0, bytesArray.length);
    return bytesArray;
}

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

If one does not know anything about the internal state of the given (Direct)ByteBuffer and wants to retrieve the whole content of the buffer, this can be used:

ByteBuffer byteBuffer = ...;
byte[] data = new byte[byteBuffer.capacity()];
((ByteBuffer) byteBuffer.duplicate().clear()).get(data);

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.

참고URL : https://stackoverflow.com/questions/679298/gets-byte-array-from-a-bytebuffer-in-java

반응형