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

  1. Start with "cat"
  2. Do this Encode the UTF-8 bytes
  3. Result "Y2F0"
Decoding the four Base64 characters returns the original three letters.

Apply it to a real problem

  1. Start with A label reading Café
  2. Do this Encode for a text field, then decode
  3. Result Café
UTF-8 keeps the accent intact through the round trip.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
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));
    }
}
Output
Q2Fmw6k=
Café

Official Java documentation