Java Convert Byte Array to Base64 String
Tags: Java Base64
In this Java tutorial we learn how to use the java.util.Base64 class to encode a byte[] array into Base64 String in Java programming language.
How to convert byte[] array to Base64 String in Java
In Java to convert a byte[] array to Base64 String we can use the Base64.getEncoder().encodeToString() method.
byte[] byteData = new byte[] {83, 105, 109, 112, 108, 101, 32, 83, 111, 108, 117, 116, 105, 111, 110};
String base64String = Base64.getEncoder().encodeToString(byteData);
The Java example code below to show you how to use the Base64.getEncoder().encodeToString() in a Java program to convert byte[] array to Base64 String.
ByteArrayToBase64StringExample1.java
import java.util.Base64;
public class ByteArrayToBase64StringExample1 {
public static void main(String... args) {
byte[] byteData = new byte[] {83, 105, 109, 112, 108, 101, 32, 83, 111, 108, 117, 116, 105, 111, 110};
String base64String = Base64.getEncoder().encodeToString(byteData);
System.out.println("Bytes Data:");
for(byte b: byteData) {
System.out.print(b);
}
System.out.println("\nBase64 String:");
System.out.println(base64String);
}
}
Bytes Data:
831051091121081013283111108117116105111110
Base64 String:
U2ltcGxlIFNvbHV0aW9u
Happy Coding 😊