javaarraysstring

How to convert a byte array to a String in Java, and skip all null bytes?


I have a byte array that's contains a string at the end of the array, and the beginning of the array is padded with zeroes. I'm using the following code to convert it to a string:

String myText = new String(byteArray, "UTF-8");

However, I'm getting a bunch of weird characters prepended to the string, due to the 0 padding. How do I get rid of it?


Solution

  • Use the String(byte[], int, int, String) constructor.

    The first int is an offset through the byte[]: just look for the first non-zero byte; the second int is the number of bytes. So, call like:

    new String(
        byteArray, firstNonNullByte, byteArray.length - firstNonNullByte, "UTF-8");