Since Java 8 the JDK includes java.util.Base64, which replaces older options such as sun.misc.BASE64Encoder (removed) and Apache Commons Codec (still fine, but no longer necessary).
Three flavours
| Factory | Alphabet | Line breaks |
|---|---|---|
Base64.getEncoder() / getDecoder() |
+ / |
none; decoder rejects them |
Base64.getUrlEncoder() / getUrlDecoder() |
- _ |
none |
Base64.getMimeEncoder() / getMimeDecoder() |
+ / |
\r\n every 76 chars; decoder ignores invalid chars |
Strings
import java.nio.charset.StandardCharsets;
import java.util.Base64;
String b64 = Base64.getEncoder().encodeToString("Grüße 👋".getBytes(StandardCharsets.UTF_8));
String text = new String(Base64.getDecoder().decode(b64), StandardCharsets.UTF_8);
Always pass a charset: getBytes() without one uses the platform default, which differs between servers (before Java 18).
URL-safe without padding (JWT style)
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
byte[] back = Base64.getUrlDecoder().decode(token); // padding is optional when decoding
Handling invalid input
The basic decoder throws IllegalArgumentException for characters outside the alphabet, including line breaks:
try {
byte[] data = Base64.getDecoder().decode(input);
} catch (IllegalArgumentException e) {
// "Illegal base64 character a" -> the hex code of the bad character
}
If the value comes from e-mail or PEM and contains newlines, use getMimeDecoder().
Files and streams
byte[] file = Files.readAllBytes(Path.of("report.pdf"));
String b64 = Base64.getEncoder().encodeToString(file);
try (OutputStream out = Base64.getEncoder().wrap(Files.newOutputStream(Path.of("big.b64")));
InputStream in = Files.newInputStream(Path.of("big.bin"))) {
in.transferTo(out);
}
wrap() streams data without loading everything into memory.
Android
On Android API 26+ use java.util.Base64. For older versions use android.util.Base64 with flags such as Base64.NO_WRAP; without that flag it inserts line breaks.
Test your output with the Base64 decoder or the standard detector.
Comments (0)
Questions, ideas or a bug in “Base64 in Java”? Leave a comment, rate the tool, or reply to others.
No comments yet. Be the first to share your feedback!