In this source code example, we show you how to encode (Base64) any arbitrary text in Java using the Base64 API that was introduced in Java 8.
Base64 is a binary-to-text encoding scheme that represents binary data in a printable ASCII string format.Java Base64 Encode Example
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
class Base64EncodeExample {
private static String base64Encode(String value) {
try {
return Base64.getEncoder()
.encodeToString(value.getBytes(StandardCharsets.UTF_8.toString()));
} catch(UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
}
public static void main(String[] args) {
String data = "sourcecode:examples!?$*&()'-=@~";
String encodedData = base64Encode(data);
System.out.println("encodedData -> " + encodedData);
}
}
Output:encodedData -> c291cmNlY29kZTpleGFtcGxlcyE/JComKCknLT1Afg==
References
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course