How to convert byte[] array to String in Java

In Java, we can use new String(bytes, StandardCharsets.UTF_8) to convert a byte[] to a String.


  // string to byte[]
  byte[] bytes = "hello".getBytes(StandardCharsets.UTF_8);

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

Table of contents

1. byte[] in text and binary data

For text or character data, we use new String(bytes, StandardCharsets.UTF_8) to convert the byte[] to a String directly. However, for cases that byte[] is holding the binary data like the image or other non-text data, the best practice is to convert the byte[] into a Base64 encoded string.


  // convert file to byte[]
  byte[] bytes = Files.readAllBytes(Paths.get("/path/image.png"));

  // Java 8 - Base64 class, finally.

  // encode, convert byte[] to base64 encoded string
  String s = Base64.getEncoder().encodeToString(bytes);

  System.out.println(s);

  // decode, convert base64 encoded string back to byte[]
  byte[] decode = Base64.getDecoder().decode(s);

  // This Base64 encode decode string is still widely use in
  // 1. email attachment
  // 2. embed image files inside HTML or CSS

Note

  • For text data byte[], try new String(bytes, StandardCharsets.UTF_8).
  • For binary data byte[], try Base64 encoding.

2. Convert byte[] to String (text data)

The below example convert a string to a byte array or byte[] and vice versa.

Warning
The common mistake is trying to use the bytes.toString() to get the string from the bytes; The bytes.toString() only returns the address of the object in memory, NOT converting byte[] to a string! The correct way to convert byte[] to string is new String(bytes, StandardCharsets.UTF_8).

ConvertBytesToString2.java

package com.mkyong.string;

import java.nio.charset.StandardCharsets;

public class ConvertBytesToString2 {

  public static void main(String[] args) {

      String str = "This is raw text!";

      // string to byte[]
      byte[] bytes = str.getBytes(StandardCharsets.UTF_8);

      System.out.println("Text : " + str);
      System.out.println("Text [Byte Format] : " + bytes);

      // no, don't do this, it returns the address of the object in memory
      System.out.println("Text [Byte Format] toString() : " + bytes.toString());

      // convert byte[] to string
      String s = new String(bytes, StandardCharsets.UTF_8);
      System.out.println("Output : " + s);

      // old code, UnsupportedEncodingException
      // String s1 = new String(bytes, "UTF_8");

  }

}

Output

Terminal

Text : This is raw text!
Text [Byte Format] : [B@372f7a8d
Text [Byte Format] toString() : [B@372f7a8d
Output : This is raw text!

3. Convert byte[] to String (binary data)

The below example converts an image phone.png into a byte[], and uses the Java 8 Base64 class to convert the byte[] to a Base64 encoded String.

Later, we convert the Base64 encoded string back to the original byte[] and save it into another image named phone2.png.

ConvertBytesToStringBase64.java

package com.mkyong.string;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class ConvertBytesToStringBase64 {

    public static void main(String[] args) {

        String filepath = "/Users/mkyong/phone.png";
        Path path = Paths.get(filepath);

        if (Files.notExists(path)) {
            throw new IllegalArgumentException("File is not exists!");
        }

        try {

            // convert the file's content to byte[]
            byte[] bytes = Files.readAllBytes(path);

            // encode, byte[] to Base64 encoded string
            String s = Base64.getEncoder().encodeToString(bytes);
            System.out.println(s);

            // decode, Base64 encoded string to byte[]
            byte[] decode = Base64.getDecoder().decode(s);

            // save into another image file.
            Files.write(Paths.get("/Users/mkyong/phone2.png"), decode);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Output

Terminal

  bh5aLyZALN4othXL2mByHo1aZA5ts5k/uw/sc7DBngGY......

  # if everything ok, it save the byte[] into a new image phone2.png

4. Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-string

5. References

25 comments on “How to convert byte[] array to String in Java

  1. this worked for me thanks a lot. i used it to decode parquet data and then write that data to parquet file. worked

    Reply
  2. Could you please help to show converting a string to a Java object ?

    Reply
  3. Why do you specify the encoding UTF-8 when converting from bytes to string, but not string to bytes? I think when you call the “getBytes” method you should also pass StandardCharsets.UTF_8, otherwise you will get a result using the platform default encoding, which may be UTF-16. When you convert back to a string, and specify the encoding of UTF-8 specifically, it won’t work if that was a UTF-16 string with supplementary characters.

    Reply
  4. Thanks for the information. Could you also please let me know how to convert Byte[] (capital B) to String. The above code does not work for the nonprimitive Byte[]. Thank you.

    Regards,
    Amar

    Reply
    1. Byte is a class, its not a datatype. Whereas byte[] array is a datatype. It will be more clear from the code snippet below:

      //—————————————————————————————————————————-//
      public static void main (String[] args){

      byte b = 18;
      Byte wrappedByte = new Byte(b);

      }

      //—————————————————————————————————————————-//

      Reply
    2. Byte[] and byte[] are incompatible (you can google “boxed primitive arrays” for more info). You probably need to explicitly convert, like

      //assume you have a value Byte[] bytes
      byte[] primitiveArray = new byte[bytes.length];
      for (int i = 0; i < bytes.length; i++) {
      primitiveArray[i] = bytes[i].byteValue();
      }
      String s = new String(primitiveArray, StandardCharsets.UTF_8);
      //…etc

      Reply
  5. please tell me a program source code in java that convert text to binary and binary to text.

    Reply
    1. If you want to find the binary of a singular alphabet, then you can make use of Ascii codes as given below:
      //—————————————————————————————————————————//
      public class TexttoBinary {

      public static void main (String[] args){

      char ch=’A’;
      System.out.println((int)ch); // prints ASCII of ‘A’
      String text = Integer.toBinaryString(ch); // converts ASCII value to Binary
      System.out.println(text);

      }

      }
      //————————————————————————————————————————-//
      If you wish to convert text strings to binary then you can use the below mentioned code:
      //————————————————————————————————————————-//
      import java.math.BigInteger;
      import java.nio.charset.Charset;

      public class TexttoBinary {

      public static void main (String[] args){

      String str = “Java”;
      String hex = toHex(str); // converts String to hexadecimal format
      String binary = hexToBinary(hex); // converts Hexadecimal string to binary format
      System.out.println(binary);
      }
      public static String toHex(String arg) {
      return String.format(“%040x”, new BigInteger(1, arg.getBytes(Charset.defaultCharset())));
      }
      static String hexToBinary(String s) {
      return new BigInteger(s, 16).toString(2);
      }

      }

      Reply
  6. Thanks sir! Saved me several hours. You are awesome!

    Reply
  7. I am trying to convert bytes into String. I am reading the image data and storing into byte array. then i think bytes length is so much. Is there any limit for bytes length? Will there be anyloss of data when converting bytes into string.

    Reply
  8. The issue I find with this byte string conversion is starting from byte{], convert it to String, then retrieve the original byte{} again!

    The most stable solution I found so far is using sun.misc.BASE64Encoder().encode(myByte) and sun.misc.BASE64Decoder().decodeBuffer(myString) but with a java sun warning!

    Any one with a better solution?

    Reply
  9. oh, thanks a lot. this simple code help me very much.

    Reply
  10. you are really a good webmaster. The web site loading speed is incredible. It sort of feels that you are doing any distinctive trick. In addition, The contents are masterpiece. you’ve performed a magnificent activity on this subject!

    Reply
  11. Thank you so much for this! I looked for quite a while before discovering this simple solution. Really appreciate it!

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *