How to Base64 Encode a String in Java


Quick solution

In short, you can just do this:

new String(Base64.getEncoder().encode(bytes));

Examples and an explanation

In Java 8 and above, you just need to import the Base64 class:

import java.util.Base64;

Then use the Base64 static methods as follows:

byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));

byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));

If you want to directly encode a string and get the result as an encoded string:

String encodeBytes = Base64.getEncoder()
    .encodeToString(("Your String").getBytes());