Java byte[] 到 String 在分配给 String 时不起作用

Java byte[] to String not working when assigned to String

我正在使用 Kafka 并遵循本教程 (https://cwiki.apache.org/confluence/display/KAFKA/Consumer+Group+Example)

经过一些调整后,代码编译并且一切正常运行。我的问题是我正在尝试利用 Kafka 服务器发送给我的字节数组来进行一些处理。如果我使用默认代码,一切正常,字节数组被转换为字符串并显示在我的屏幕上。如果我尝试读取字节数组并将其分配给一个字符串,以便我可以将它显示在屏幕上然后解析它,则什么也不会发生。

it.next().message() returns a byte array

默认代码:

ConsumerIterator<byte[], byte[]> it = m_stream.iterator();
while (it.hasNext())
    System.out.println("Thread " + m_threadNumber + ": " + new String(it.next().message()));

我的代码有问题:

 ConsumerIterator<byte[], byte[]> it = m_stream.iterator();
 String msg= "";
 while (it.hasNext())
    msg = new String(it.next().message());
    System.out.println("Thread " + m_threadNumber + ": " + msg);

谁能告诉我为什么我不能将字节数组分配给我的字符串?当然还有如何解决我的故障?

我看过了:

Java byte to string

Convert byte to string in Java

converting byte[] to string

但其中 none 似乎适用,它们都试图在字符串初始化时将字节数组分配给字符串,我不能在这里这样做。

您缺少大括号,因此您的 println 仅在最后一次执行。试试这个:

ConsumerIterator<byte[], byte[]> it = m_stream.iterator();
String msg= "";
while (it.hasNext())
{
   msg = new String(it.next().message());
   System.out.println("Thread " + m_threadNumber + ": " + msg);
}

您的代码失败是因为您没有将代码块括在大括号中。调整您的代码显示:

ConsumerIterator<byte[], byte[]> it = m_stream.iterator();
while (it.hasNext()) { // <- here
    String msg = new String(it.next().message());
    System.out.println("Thread " + m_threadNumber + ": " + msg);
} // <- and here

事实上,有了这些大括号,这个代码片段就等同于您的第一个代码片段。

顺便说一句:不需要在循环外声明变量msg

只需在循环块中放入大括号即可。

while (it.hasNext()){msg = new String(it.next().message());
System.out.println("Thread " + m_threadNumber + ": " + msg);}