Convert Byte Array to Base64 String in Java

Convert byte array to base64 String in java

In this article, we will see how to convert byte array to base64 String in java.

Using Base64 to Convert Byte Array to Base64 String in Java [ Java 8+]

Java 8 has finally introduced Base64 functionalities via java.util.Base64 class.

You can use Base64's encode() method to convert Byte Array to Base64 String in Java. It encodes input without any line separation.
Here is simple code:

Output:

SmF2YTJibG9n
SmF2YTJibG9n

In base64, length of encoded String should be multiple of 3. Sometimes, encode appends one or two padding characters to make it multiple of 3.

In case, you don’t want to append extra padding characters, you can skip padding using withPadding() method. This is useful when you already know that you are not going to decode this String back.
Here is the code:

Using Apache Common Codec to Convert Byte Array to Base64 String in Java [ < Java 8]

If you are using Java 7 or below version. there is no direct utility class to convert Byte Array to Base64 String in Java.

You can use Apache common codec’s Base64 class to achieve the same.
You need to add following dependenices in your pom.xml.

Output:

SmF2YTJibG9n
SmF2YTJibG9n

Using Base64Utils to Convert Byte Array to Base64 String in Spring

if you are using Spring in your project, you can use Base64Utils to convert Byte Array to Base64 String in java. It provides exact same functions as java.util.Base64.
You need to add following dependenices in your pom.xml.

Output:

SmF2YTJibG9n
SmF2YTJibG9n

Using android.util.Base64 to Convert Byte Array to Base64 String in Android

if you are using android in your project, you can use android.util.Base64 to convert Byte Array to Base64 String in java. It provides exact same functions as java.util.Base64.

Output:

SmF2YTJibG9n
SmF2YTJibG9n

That’s all about how to convert Byte Array to Base64 String in java.

Was this post helpful?

Leave a Reply

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