How to convert "java.nio.HeapByteBuffer" to String

I have a java.nio.HeapByteBuffer [pos = 71098 lim = 71102 cap = 94870] data structure that I need to convert to Int (in Scala), the conversion might look simple, but regardless, I didn't get the correct conversion. Can you help me?

Here is my code snippet:

val v : ByteBuffer= map.get("company").get
val utf_str = new String(v, java.nio.charset.StandardCharsets.UTF_8)
println (utf_str)

      

the output is just "R" ??

+1


source to share


1 answer


I don't see how you can get this to compile, String has constructors that take another string, or perhaps an array, but not ByteBuffer or any of its parents.

To work with nio buffer api you write to buffer first and then flip before reading from buffer, there are many good resources on the internet. For example this: http://tutorials.jenkov.com/java-nio/buffers.html

How to read this as a string depends entirely on how the characters are encoded inside the buffer, if they are two bytes per character (since strings are in Java / JVM) you can convert your buffer to a character buffer 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!")

      

+1


source







All Articles