Java – converting byte[] to string

java

I am having a bytearray of byte[] type having the length 17 bytes, i want to convert this to string and want to give this string for another comparison but the output i am getting is not in the format to validate, i am using the below method to convert.I want to output as string which is easy to validate and give this same string for comparison.

    byte[] byteArray = new byte[] {0,127,-1,-2,-54,123,12,110,89,0,0,0,0,0,0,0,0};
    String value = new String(byteArray);
    System.out.println(value);

Output : ���{nY

Best Answer

What encoding is it? You should define it explicitly:

new String(byteArray, Charset.forName("UTF-32"));  //or whichever you use

Otherwise the result is unpredictable (from String.String(byte[]) constructor JavaDoc):

Constructs a new String by decoding the specified array of bytes using the platform's default charset

BTW I have just tried it with UTF-8, UTF-16 and UTF-32 - all produce bogus results. The long series of 0 makes me believe that this isn't actually a text. Where do you get this data from?

UPDATE: I have tried it with all character sets available on my machine:

for (Map.Entry<String, Charset> entry : Charset.availableCharsets().entrySet())
{
    final String value = new String(byteArray, entry.getValue());
    System.out.println(entry.getKey() + ": " + value);
}

and no encoding produces anything close to human-readable text... Your input is not text.