Base64 Java encode and decode a string
To encode and decode a string in Base64 in Java, you can use the java.util.Base64
class. Here's an example:
// Encode
String originalString = "Hello, World!";
String encodedString = Base64.getEncoder().encodeToString(originalString.getBytes());
System.out.println(encodedString); // Outputs "SGVsbG8sIFdvcmxkIQ=="
// Decode
byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);
System.out.println(decodedString); // Outputs "Hello, World!"
Note that the Base64
class was introduced in Java 8, and it replaces the sun.misc.BASE64Encoder
and sun.misc.BASE64Decoder
classes that were deprecated in Java 9.
I hope this helps! Let me know if you have any other questions.