How to convert byte[] array to String in Java and vice versa?

  1. Accepted Answer

Accepted Answer

To convert a byte array to a String, you must know its encoding. If the byte array contains text data, you can easily convert it to a String using String’s constructor.

byte[] bytes = ...
String str = new String(bytes, StandardCharsets.UTF_8); // // byte[] to string for UTF_8 encoding

To get the original byte array back from String:

// string to byte[] for UTF_8 encoded byte array
byte[] bytes = str.getBytes();

Byte arrays mostly contain binary data such as an image. If the byte array that you are trying to convert to String contains binary data, then none of the text encodings (UTF_8 etc.) will work. If you convert binary data to a String using UTF encoding and then decode it back, the result will be different from the original.

To encode arbitrary binary data from byte array to String, the safest way is to use Base64 encoding. Base64 is binary-to-text encoding for representing binary data in ASCII string format.

You can use Base64 encoding on any type of array without worrying about encodings, etc. When possible, prefer this way of converting byte arrays and Strings.

byte[] bytes = ...

// encode binary byte array to Base64 String
String str = Base64.getEncoder().encodeToString(bytes);


// decode Base64 String to byte array
byte[] decode = Base64.getDecoder().decode(s);

Speak Your Mind