In Java, you can use the Base64
class in the java.util
package to encode and decode data in Base64.
To encode data in Base64, you can use the getEncoder()
method to obtain an encoder, and then use the encodeToString()
method to perform the encoding:
Copy codeimport java.util.Base64;
public class Main {
public static void main(String[] args) {
String originalString = "Hello World!";
String encodedString = Base64.getEncoder().encodeToString(originalString.getBytes());
System.out.println("Encoded String: " + encodedString);
}
}
To decode data from Base64, you can use the getDecoder()
method to obtain a decoder, and then use the decode()
method to perform the decoding:
Copy codeimport java.util.Base64;
public class Main {
public static void main(String[] args) {
String encodedString = "SGVsbG8gV29ybGQh";
byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);
System.out.println("Decoded String: " + decodedString);
}
}
It is important to notice that the above examples are using the Base64 encoding that is URL and Filename safe, which uses ‘-‘ and ‘_’ instead of ‘+’ and ‘/’ .