Quick solution
In short, you can just do this:
1
|
new String(Base64.getEncoder().encode(bytes));
|
Examples and an explanation
In Java 8 and above, you just need to import the Base64 class:
1
|
import java.util.Base64;
|
Then use the Base64 static methods as follows:
1
2
3
4
5
|
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:
1
2
|
String encodeBytes = Base64.getEncoder()
.encodeToString(("Your String").getBytes());
|