How to convert “java.nio.HeapByteBuffer” to String

前端 未结 1 1397
醉梦人生
醉梦人生 2021-01-16 06:35

I have a data structure java.nio.HeapByteBuffer[pos=71098 lim=71102 cap=94870], which I need to convert into Int (in Scala), the conversion might look simple but whatever w

相关标签:
1条回答
  • 2021-01-16 07:17

    I can't see how you can even get that to compile, String has constructors that accepts another string or possibly an array, but not a ByteBuffer or any of its parents.

    To work with the nio buffer api you first write to a buffer, then do a flip before you read from the buffer, there are lots of good resources online about that. This one for example: http://tutorials.jenkov.com/java-nio/buffers.html

    How to read that as a string entirely depends on how the characters are encoded inside the buffer, if they are two bytes per character (as strings are in Java/the JVM) you can convert your buffer to a character buffer by using asCharBuffer.

    So, for example:

    val byteBuffer = ByteBuffer.allocate(7).order(ByteOrder.BIG_ENDIAN);
    byteBuffer.putChar('H').putChar('i').putChar('!')
    byteBuffer.flip()
    val charBuffer = byteBuffer.asCharBuffer
    assert(charBuffer.toString == "Hi!")
    
    0 讨论(0)
提交回复
热议问题