Java 调用者可以在从 class 返回的字节缓冲区中找到空字符,但在遍历 class 中的字节缓冲区时找不到

Java caller can find null character in bytebuffer returned from class but not when iterating through the bytebuffer in the class

我有以下代码可以在 Java 中遍历充满 charsbytebuffer 并构建 string.

      StringBuilder actualString = new StringBuilder();

      for(int i = 0; i < length; i++)
       {
            if((char)bbuf.get(i) != '[=13=]');
            {
                actualString.append((char)bbuf.get(i));
                System.out.println("ascii code is " + bbuf.get(i));
            }
        }

当使用 class 的调用者获取 bytebuffer 并迭代调用者函数的位置时遇到 [=21=](空终止符)时代码工作正常并停止包含。

例如

new bufclass = bufclass

buffclass.getbytebuffer

run code from above

然而,当我在创建 bytebuffer 之后放置该代码并将其分配到包含 bytebuffer 的 class 中时,它永远不会停在 [=21=] 字符处。

一个如何完成的例子是

create bytebuffer and allocate bytebuffer

run code to iterate from above

为什么我的代码在使用 class 的调用方迭代 bytebuffer 以获取 bytebuffer 时有效,但在将代码添加到 [= 时却不起作用45=] 包含 bytebuffer?

请注意,这是我打印 ASCII 字符代码时的结果,是的,我确实尝试了 if the byte is equal to 0,但也没有用。

ascii code is 116
ascii code is 101
ascii code is 115
ascii code is 116
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0
ascii code is 0

您的 if 语句后有一个 ;

if((char)bbuf.get(i) != '[=10=]');

这在功能上等同于

if((char)bbuf.get(i) != '[=11=]') {
}

所以,删除 ; 就可以了。