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

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.favtuts.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

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.favtuts.string;

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 = ClassLoader.getSystemResource("phone.png").getFile();
        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
            // current directory            
            Path cwd = Path.of("").toAbsolutePath();            
            System.out.println(cwd.toString());

            Files.write(Paths.get(cwd.toString() + "/phone2.png"), decode);

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

Output

  bh5aLyZALN4othXL2mByHo1aZA5ts5k/uw/sc7DBngGY......

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

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-string

References

Leave a Reply

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