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.
댓글 (0)
“Base64 in Java”에 대한 질문, 아이디어, 버그가 있으신가요? 댓글을 남기거나 도구를 평가하거나 다른 사람에게 답글을 달아 주세요.
아직 댓글이 없습니다. 첫 번째로 의견을 남겨 주세요!