4

I have a byte array which looks like this:

[0, 0, 0, 0, 0, 0, 0, 0, 122, 98, 117, 54, 46, 0, 0, 115, 122, 42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 116, 121, 116, 117, 108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 107, 111, 98, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 122, 42, 109, 111, 119, 40, 0, 0, 0, 0, 0, 0, 107, 111, 98, 0, 0, 0, 0, 0, 98, 111, 40]

I wanted to print it as a string, so I wrote the following code:

System.out.println(new String(byteArray));

but there is no output. Next, I tried the following code:

for (byte b : byteArray) {
    System.out.print((char) b);
}

but again there is no output. But when I tried the following code:

for (byte b : byteArray) {
    System.out.println((char) b);
}

I was able to see the values.

My question is, why can't I create a string or why did the first printing of values from byteArray fail?

Rop
  • 217
  • 2
  • 12

4 Answers4

0

try this

System.out.println(Arrays.toString(byteArray));
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

Try this.

byte[] bytes = new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 122, 98, 117, 54, 46, 0, 0, 115, 122, 42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 116, 121, 116, 117, 108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 107, 111, 98, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 122, 42, 109, 111, 119, 40, 0, 0, 0, 0, 0, 0, 107, 111, 98, 0, 0, 0, 0, 0, 98, 111, 40};
System.out.println(new String(bytes));
Ryan T. Grimm
  • 1,307
  • 1
  • 9
  • 17
0

Your byte array is mostly non printable characters, with a few random letters mixed in. But all you need is:

String myString = new String(byteArray);

which will give you a valid string.

Try out the following code, as maybe it will better illustrate the issue your having:

for (char c : new String(byteArray).toCharArray()) {
    System.out.printf("Character: %s Hex: %02x \n", c, (int) c);
}
James Kidd
  • 444
  • 4
  • 8
0

You can use a String(byte[],Charset) constructor and specify a Charset to be used to decode this array of bytes:

System.out.println(new String(byteArray, StandardCharsets.UTF_8));

In most cases, StandardCharsets.UTF_8 is a default charset.