This tutorial will teach you how to convert an array of bytes to a string of characters in Java.
Additionally, you might be interested in learning how to convert an image/file byte[] array to a Base64 encoded String. If you are, then check the following tutorial.
Converting String to byte[]
Let’s assume we have a simple line of text converted to an array of bytes.
byte[] helloWorldBytes = "Hello world".getBytes(StandardCharsets.UTF_8);
Now that we have an array of bytes, we would like to convert it back to a String.
Converting byte[] to String
String helloWorldString = new String(helloWorldBytes, StandardCharsets.UTF_8);
Below is a complete code example that demonstrates:
- How to convert a plain text to an array of bytes in Java. And then,
- How to convert a byte[] array back to a String value.
import java.nio.charset.StandardCharsets; public class App { public static void main(String[] args) { byte[] helloWorldBytes = "Hello world".getBytes(StandardCharsets.UTF_8); String helloWorldString = new String(helloWorldBytes, StandardCharsets.UTF_8); System.out.println(helloWorldString); } }
Converting byte[] to a Base64 Encoded String
Sometimes we need to convert the byte[] array to a Base64 encoded String. This is helpful when you need to send an array of bytes over the network.
To convert an array of bytes to a Base64 encoded String, you will use the Base64 java class from the java.util package.
String base64EncodedString = Base64.getEncoder().encodeToString(helloWorldBytes);
Below is a complete code example demonstrating how to encode an array of bytes to a Base64 encoded String in Java.
import java.nio.charset.StandardCharsets; import java.util.Base64; public class App { public static void main(String[] args) { byte[] helloWorldBytes = "Hello world".getBytes(StandardCharsets.UTF_8); String base64EncodedString = Base64.getEncoder().encodeToString(helloWorldBytes); System.out.println(base64EncodedString); } }
Decoding Base64 String to byte[]
A Base64 encoded string can be easily decoded back to a byte[] array.
byte[] bytesFromBase64String = Base64.getDecoder().decode(base64EncodedString);
I hope this very short blog post was helpful to you.
There are many other useful tutorials you can find on this site. To find Java-related tutorials, check out the Java tutorials page.
Happy learning!