Convert Java string to byte array Convert Java string to byte array arrays arrays

Convert Java string to byte array


You used array.toString(), which is implemented like this:

return "[B@" + Integer.toString(this.hashCode(), 16);

(In fact it inherits the definition from Object, and the part before the @ simply is the result of getClass().getName().)

And the hashCode here does not depend on the content.

Instead, use new String(array, encoding).

Of course, this only works for byte-arrays which are really representable as Java strings (which then contain readable characters), not for arbitrary arrays. There better use base64 like Bozho recommended (but make sure to use it on both sides of the channel).


This looks like Base64. Take a look at commons-codec Base64 class.


You can't just use getBytes() on two different machines, since getBytes uses the plattform's default charset.

Decode and encode the array with a specified charset (i.e. UTF-8) to make sure you get the correct results.