【问题标题】:Java byte[] to String not working when assigned to String分配给 String 时,Java byte[] 到 String 不起作用
【发布时间】:2016-03-31 04:53:17
【问题描述】:

我正在使用 Kafka 并按照本教程进行操作 (https://cwiki.apache.org/confluence/display/KAFKA/Consumer+Group+Example)

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

it.next().message() 返回一个字节数组

默认代码:

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

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

【问题讨论】:

  • 你得到什么错误信息?
  • 另外,为什么你的while循环周围没有大括号?
  • 没有错误信息。屏幕上什么都没有显示
  • 请比“它坏了”更准确地描述问题
  • 好吧,我在办公桌前坐得太久了。默认代码只执行那一行,所以我不需要括号。当我添加额外的行时,我违反了一个有一段时间的假设。感谢@Juan,因为我在登记入住时得到了第一个答案(老实说,我欠你一个道歉,因为我对此嗤之以鼻。很抱歉对你的回复有不良想法)我会尽快接受它,我会尽快接受跨度>

标签: java arrays string bytearray apache-kafka


【解决方案1】:

您缺少大括号,因此您的 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);
}

【讨论】:

    【解决方案2】:

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

    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
    

    事实上,有了这些花括号,这段代码 sn-p 就相当于你的第一个代码 sn-p。

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

    【讨论】:

      【解决方案3】:

      只需要在while循环块中加上花括号。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-29
        • 1970-01-01
        • 2021-09-26
        • 1970-01-01
        • 2017-09-14
        • 1970-01-01
        相关资源
        最近更新 更多