如何转换"java.nio.HeapByteBuffer"?到字符串 [英] How to convert "java.nio.HeapByteBuffer" to String

查看:51
本文介绍了如何转换"java.nio.HeapByteBuffer"?到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据结构java.nio.HeapByteBuffer [pos = 71098 lim = 71102 cap = 94870],我需要将其转换为Int(在Scala中),转换看起来很简单,但是无论我采用哪种方法,我都做了无法正确转换.你能帮我吗?

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?

这是我的代码段:

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

输出仅为"R" ??

the output is just "R" ??

推荐答案

我什至看不到如何编译它,String的构造函数接受另一个字符串或可能的数组,但不接受ByteBuffer或任何一个它的父母.

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.

要使用nio缓冲区api,您首先要写入缓冲区,然后在从缓冲区读取之前进行一次翻转,在线上有很多不错的资源.例如: http://tutorials.jenkov.com/java-nio/buffers.html

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

如何将其理解为字符串完全取决于缓冲区中字符的编码方式,如果每个字符两个字节(如Java/JVM中的字符串),则可以使用以下命令将缓冲区转换为字符缓冲区asCharBuffer.

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.

例如,

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

这篇关于如何转换"java.nio.HeapByteBuffer"?到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆