Appearance
Decode Base64 data in Java
To decode base64 data in Java, you can use the Base64.Decoder class introduced in Java 8. Here's an example of how to use it:
java
import java.util.Base64;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
String base64String = "SGVsbG8gV29ybGQh";
byte[] data = Base64.getDecoder().decode(base64String);
String text = new String(data, StandardCharsets.UTF_8);
System.out.println(text);
}
}This will print the following output:
console
Hello World!The Base64.getDecoder() method returns a Base64.Decoder object that can be used to decode base64 data. The decode() method of the Base64.Decoder class takes a base64 encoded string as an argument and returns a byte array containing the decoded data. Note that it throws an IllegalArgumentException if the input contains characters outside the Base64 alphabet or has incorrect padding.
To encode data to base64, you can use the Base64.Encoder class in a similar way:
java
import java.util.Base64;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
String text = "Hello World!";
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64String = Base64.getEncoder().encodeToString(data);
System.out.println(base64String);
}
}This will print the following output:
console
SGVsbG8gV29ybGQhNote that the Base64 class is part of the Java SE standard library, so you don't need to include any additional libraries to use it.