0

I am using Kafka and following along with this tutorial (https://cwiki.apache.org/confluence/display/KAFKA/Consumer+Group+Example)

After some tweaks, the code compiles and everything runs like it should. my problem is that I am trying to utilize an array of bytes that the Kafka server sends me to do some processing. If I use the default code, everything works fine and the byte array gets converted to a String and displayed on my screen. If I try to read the byte array and assign it to a String so that I can display it to the screen and then parse it nothing happens.

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

Default code:

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

My Code that breaks:

 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);

Can anybody tell me why I cannot assign the byte array to my String? And of course how to fix my glitch?

I've taken a look at:

Java byte to string

Convert byte to string in Java

converting byte[] to string

but none of them seem to apply, they all try to assign the byte array to the String as the String is initialized and I cannot do that here.

Community
  • 1
  • 1
Semicolons and Duct Tape
  • 2,927
  • 4
  • 20
  • 35

3 Answers3

4

You are missing the curly brackets so your println is only being executed the last time. Try this:

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);
}
Juan
  • 3,675
  • 20
  • 34
3

Your code is failing because you did not enclose your code block in braces. Adjusting your code reveals:

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

In fact, with these braces this code snippet is equivalent to your first code snippet.

By the way: No need to declare the variable msg outside the loop.

Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66
0

Just put curly braces while loop block.

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