Gray and brown mountain

Converting byte array to string and vice versa in Java

This article contains information on how to convert a byte array to string in Java. Also, you will see how to convert the string in the opposite direction. Such an operation is very simple. However, Java provides different methods that you can use in your code. As a result, we've decided to review the most popular methods. Please see the following sections and decide which solution is applicable to your specific needs.

Converting byte array to string

Before converting data to the string, you need to define the array that holds the actual values. In a real life application, you may read those values from the disk or obtain them from the network. However, in our specific case, we define a simple array that contains a list of bytes.

Then, we use the String class to convert the byte array to string. Also, we specify that the string uses the UTF8 encoding. Please see the implementation below.

import java.nio.charset.StandardCharsets;

class sample {
    public static void main(String args[]) {
        final byte[] contentBytes =
            new byte[]{77, 105, 108, 107, 121, 32, 87, 97, 121};

        final String content = new String(contentBytes, StandardCharsets.UTF_8);

        System.out.println(content);
    }
}

If you run the given code, the output should be like below. As you see, there is the "Milky Way" string in the console.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
Milky Way

Converting string to byte array

You may also convert the string back to the byte array. That's a simple operation as well. Java provides getBytes() method that allows you to get the array with data. Also, you may specify encoding of the string, which is UTF8 in our case.

Please see the following sample that demonstrates how it should be done correctly.

import java.util.Arrays;
import java.nio.charset.StandardCharsets;

class sample {
    public static void main(String args[]) {
        final String content = "Milky Way";

        final byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);

        System.out.println(Arrays.toString(contentBytes));
    }
}

Now, you can try to run our code. The console will contain the array of bytes.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[77, 105, 108, 107, 121, 32, 87, 97, 121]

Converting byte array to string without encoding

The constructor of the String class also allows you to convert the data without specifying the string encoding. To do that, you have to pass a single argument only, which is an array of bytes. Please see our code sample below to see how it is done.

class sample {
    public static void main(String args[]) {
        final byte[] contentBytes =
            new byte[]{77, 105, 108, 107, 121, 32, 87, 97, 121};

        final String content = new String(contentBytes);

        System.out.println(content);
    }
}

If you run our simple application, the console should contain the "Milky Way" message.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
Milky Way

Converting string to byte array without encoding

You may also skip specifying the encoding when converting string to byte array. The getBytes() method may be called without any arguments. The code sample is given below. There, we convert the "Milky Way" string to the byte array.

import java.util.Arrays;

class sample {
    public static void main(String args[]) {
        final String content = "Milky Way";

        final byte[] contentBytes = content.getBytes();

        System.out.println(Arrays.toString(contentBytes));
    }
}

If you run the given code, the application should print a byte array to the console. The sample output is provided below.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[77, 105, 108, 107, 121, 32, 87, 97, 121]

Using Charset.decode() method to convert byte array to string

The Charset class provides the decode() method. It also can be used for converting a byte array to string. But before using that method, you have to obtain a static instance from the StandardCharsets class. In our specific case, we will use the UTF8 encoding, because it is very popular.

Please see the following sample that demonstrates the correct usage of the Charset class.

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

class sample {
    public static void main(String args[]) {
        final byte[] contentBytes =
            new byte[]{77, 105, 108, 107, 121, 32, 87, 97, 121};

        final Charset utf8Charset = StandardCharsets.UTF_8;

        final String content =
            utf8Charset.decode(ByteBuffer.wrap(contentBytes)).toString();

        System.out.println(content);
    }
}

The above code should output the "Milky Way" message to the standard console. Example is given below.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
Milky Way

Using Charset.encode() method to convert string to byte array

Also, you can do the opposite thing. The Charset class can be used to convert string to byte array. However, you have to use the encode() method in that case. You can review the following sample to see how it should be done.

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

class sample {
    public static void main(String args[]) {
        final String content = "Milky Way";

        final Charset utf8Charset = StandardCharsets.UTF_8;

        final byte[] contentBytes = utf8Charset.encode(content).array();

        System.out.println(Arrays.toString(contentBytes));
    }
}

Now, you may try to run our simple application. The console output may be like below.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[77, 105, 108, 107, 121, 32, 87, 97, 121]

Using CharsetDecoder class to convert byte array to string

Java also has the CharsetDecoder class. That is a low-level engine that works with the data. You can use it to directly decode the values from one format to another.

To use it, you have to call the newDecoder() method on an instance of the relevant charset. In our case, we use UTF8 character encoding. But you can change it to any other charset if that is needed in your application.

Following is a simple application that demonstrates how to use this method of converting byte array to string.

import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;

class sample {
    public static void main(String args[]) {
        final byte[] contentBytes =
            new byte[]{77, 105, 108, 107, 121, 32, 87, 97, 121};

        final CharsetDecoder utf8Decoder = StandardCharsets.UTF_8.newDecoder();

        try {
            final String content =
                utf8Decoder.decode(ByteBuffer.wrap(contentBytes)).toString();

            System.out.println(content);
        } catch (CharacterCodingException exception) {
            exception.printStackTrace();
        }
    }
}

The same as in previous samples, if you run the given code, the console output should contain the word "Milky Way".

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
Milky Way

Using CharsetEncoder class to convert string to byte array

If you need to convert string to byte array, then you may use the CharsetEncoder class. It's the opposite of the CharsetDecoder class. Before encoding the data, you have to obtain an instance of that class with help of the newEncoder() method.

You can see our code sample below. Please pay attention that the CharBuffer.wrap() method is used there to put text content into the buffer.

import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

class sample {
    public static void main(String args[]) {
        final String content = "Milky Way";

        final CharsetEncoder utf8Encoder = StandardCharsets.UTF_8.newEncoder();

        try {
            final byte[] contentBytes =
                utf8Encoder.encode(CharBuffer.wrap(content)).array();

            System.out.println(Arrays.toString(contentBytes));
        } catch (CharacterCodingException exception) {
            exception.printStackTrace();
        }
    }
}

Now you can see the console output. There should be a list of bytes.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[77, 105, 108, 107, 121, 32, 87, 97, 121]

Converting byte array to base64 string

As you have noticed in previous sections of this tutorial, we've been reviewing only methods of converting values from one type to another. However, there is an alternative method of encoding the data. You may consider using it in your code. Java 8 contains the Base64 class. It allows you to encode binary data into a string format that can easily be transferred over the network.

There is a special algorithm that defines how each binary number must be converted into a character. As a result, any type of data can be saved in a human readable form.

Now, please review our simple application that encodes a byte array into a Base64 string.

import java.util.Base64;

class sample {
    public static void main(String args[]) {
        final byte[] contentBytes =
            new byte[]{77, 105, 108, 107, 121, 32, 87, 97, 121};

        final String content = Base64.getEncoder().encodeToString(contentBytes);

        System.out.println(content);
    }
}

If you run the given code, the console output will contain the encoded string.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
TWlsa3kgV2F5

Converting base64 string to byte array

You can also convert a Base64 string in the opposite direction. The Base64 class provides a decoder that can parse the string and return a binary data.

import java.util.Arrays;
import java.util.Base64;

class sample {
    public static void main(String args[]) {
        final String content = "TWlsa3kgV2F5";

        final byte[] contentBytes = Base64.getDecoder().decode(content);

        System.out.println(Arrays.toString(contentBytes));
    }
}

If you run the above application, the Base64 string will be decoded and stored into an array in a binary form. The console output should be like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[77, 105, 108, 107, 121, 32, 87, 97, 121]

Conclusion

That's a very popular topic in programming. Sometimes you may need to convert data from a binary format to a string and vice versa. Java already has an API that allows you to do that.

Such a code may be useful in various situations. Like the data is transferred over the network, or the data is saved to the database. In addition, you may need to convert the data for logging purposes.

Also, there is an alternative way of converting the type of binary data. You may use the Base64 class to get the encoded data in a plain string form.

Related Articles

Random numbers

How to generate a random number in Java

Very big waterfall

How to compare two strings in Java

Comments

Leave a Reply

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