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

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

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 which I approach , i did not get right conversion. could you please 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:

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!") 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!