Round-trip a Unicode label through Base64 in Java
UTF-8 converts the text to bytes. Base64 represents those bytes as ASCII text, and decoding recovers the original byte sequence.
A simple example
Encode the UTF-8 bytes
- Start with "cat"
- Do this Encode the UTF-8 bytes
- Result "Y2F0"
Apply it to a real problem
- Start with A label reading Café
- Do this Encode for a text field, then decode
- Result Café
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws Exception {
String label = "Café";
String encoded = Base64.getEncoder().encodeToString(label.getBytes(StandardCharsets.UTF_8));
byte[] restored = Base64.getDecoder().decode(encoded);
System.out.println(encoded);
System.out.println(new String(restored, StandardCharsets.UTF_8));
}
}
Q2Fmw6k= Café