CharBuffer 到字符串?

时间:2021-07-09 13:04:08

标签: kotlin charbuffer

如何从 CharBuffer 中获取字符串“hi”? toString() 似乎不起作用。

val a = CharBuffer.allocate(10);
a.put('h');
a.put('i');
val b = a.toString();

运行上述代码后的变量状态:

enter image description here enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

() => Node 是相当低级的并且真正用于 I/O 的东西,所以一开始它可能看起来不合逻辑。在您的示例中,它实际上返回了一个包含您未设置的剩余 8 个字节的字符串。要使其返回您的数据,您需要像这样调用 Node

CharBuffer

您可以在 Buffer

的文档中找到更多信息

对于更典型的用例,使用 flip() 要容易得多:

val a = CharBuffer.allocate(10);
a.put('h');
a.put('i');
a.flip()
val b = a.toString();

或者甚至使用包装 StringBuilder 的 Kotlin 实用程序:

val a = StringBuilder()
a.append('h')
a.append('i')
val b = a.toString()