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



我有以下代码来经历一个充满chars Java bytebuffer并构建一个string

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

代码工作正常,当使用类的调用方获取bytebuffer并循环访问调用方函数的包含位置时,当遇到(null 终止符)时,代码会在 处停止。

例如

new bufclass = bufclass
buffclass.getbytebuffer
run code from above

但是,当我将该代码放在bytebuffer之后并在包含bytebuffer的类中分配时,它永远不会停留在字符上。

如何做到这一点的一个例子是

create bytebuffer and allocate bytebuffer
run code to iterate from above

为什么我的代码在使用类的调用方遍历bytebuffer以获取bytebuffer时工作,但在将代码添加到包含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) != '');

这在功能上等效于

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

所以,删除那个;,你就可以开始了。

最新更新