Base64 Encoding in Java: java.util.Base64 Guide
Learn Java Base64 encoding with java.util.Base64. Examples for basic, URL-safe, MIME encoding, stream encoding, and file conversion.
How to Base64 Encode in Java
Since Java 8, the java.util.Base64 class provides three encoder/decoder pairs: Basic (standard Base64), URL-safe (uses - and _ instead of + and /), and MIME (adds line breaks every 76 characters). This replaced the older, non-standard sun.misc.BASE64Encoder that should never be used in production code.
Basic Encoding and Decoding
import java.util.Base64;
import java.nio.charset.StandardCharsets;
// Encode
String original = \"Hello, World!\";
String encoded = Base64.getEncoder()
.encodeToString(original.getBytes(StandardCharsets.UTF_8));
System.out.println(encoded); // SGVsbG8sIFdvcmxkIQ==
// Decode
byte[] decodedBytes = Base64.getDecoder().decode(encoded);
String decoded = new String(decodedBytes, StandardCharsets.UTF_8);
System.out.println(decoded); // Hello, World!
URL-Safe Encoding
Standard Base64 includes + and / which cause issues in URLs and filenames. The URL encoder replaces them:
String data = \"subjects?_d=1&page=2\";
String urlSafe = Base64.getUrlEncoder()
.encodeToString(data.getBytes(StandardCharsets.UTF_8));
// Uses - and _ instead of + and /
// Without padding (no trailing = signs)
String noPadding = Base64.getUrlEncoder().withoutPadding()
.encodeToString(data.getBytes(StandardCharsets.UTF_8));
MIME Encoding
The MIME encoder outputs lines of no more than 76 characters, separated by \\
, as required by RFC 2045 for email:
byte[] largeData = new byte[200];
String mimeEncoded = Base64.getMimeEncoder()
.encodeToString(largeData);
// Output is wrapped at 76 characters per line
Stream Encoding for Large Files
import java.io.*;
import java.util.Base64;
// Wrap an OutputStream with Base64 encoding
try (OutputStream out = Base64.getEncoder()
.wrap(new FileOutputStream(\"encoded.txt\"));
FileInputStream in = new FileInputStream(\"image.png\")) {
in.transferTo(out); // Java 9+
}
// Wrap an InputStream with Base64 decoding
try (InputStream in = Base64.getDecoder()
.wrap(new FileInputStream(\"encoded.txt\"));
FileOutputStream out = new FileOutputStream(\"decoded.png\")) {
in.transferTo(out);
}
Common Use Cases in Java
- REST API authentication — HTTP Basic Auth headers require Base64-encoded credentials
- JWT tokens — JSON Web Tokens use URL-safe Base64 for header and payload encoding
- XML/SOAP — binary data in XML messages must be Base64-encoded
- Database BLOBs — encoding binary data for storage in text-only database columns
- Cryptographic keys — PEM format certificates and keys use Base64 encoding