Java IO Tutorial

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
25 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Amar
10 years ago

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

Adam Burley
2 years ago
Reply to  Amar

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

Raptor
10 years ago
Reply to  Amar

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);

}

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

saidtak
11 years ago

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?

vj
14 years ago

thnx a lot…saved ma day 😛

pallavi
1 year ago

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

Grk
1 year ago

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

Adam Burley
2 years ago

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.

mahya
10 years ago

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

Raptor
10 years ago
Reply to  mahya

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);
}

}

subhash M
10 years ago

Thank you

Karthik SR
10 years ago

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

Abhijith
11 years ago

Thanks man. That helped.

Kalyan Kumar
11 years ago

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.

Diljeet
11 years ago

Thanks for sharing

ogda
11 years ago

Thank you 🙂

ThePCWizard
11 years ago

Thanks, for sharing such simple codes. it helps!

rohan
11 years ago

This helped and saved time for a newbie like me 🙂

LM
11 years ago

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

Marty Brouwer
11 years ago

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!

Paul
12 years ago

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