MIME Base64 Wraps Long Lines
Encode with Base64.getMimeEncoder so long payloads wrap at a fixed width, then decode the wrapped text back to the original bytes.
Code
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
byte[] payload = "The quick brown fox jumps over the lazy dog".repeat(2)
.getBytes(StandardCharsets.UTF_8);
// the MIME encoder wraps every line at the requested width
String wrapped = Base64.getMimeEncoder(20, "\n".getBytes(StandardCharsets.UTF_8))
.encodeToString(payload);
System.out.println("wrapped:");
System.out.println(wrapped);
System.out.println("lines: " + wrapped.split("\n").length);
// the MIME decoder ignores the line breaks it produced
String decoded = new String(
Base64.getMimeDecoder().decode(wrapped), StandardCharsets.UTF_8);
System.out.println("roundtrip: " + decoded.equals(new String(payload, StandardCharsets.UTF_8)));
// the basic encoder keeps everything on one line
String plain = Base64.getEncoder().encodeToString(payload);
System.out.println("plain has newline: " + plain.contains("\n"));
}
}How the snippet works
Everything happens inside the class Main and the function main.
What to watch for
- The imports (if any) point only at standard-library modules.
Applying it
Entry signature: public static void main(String[] args)
Each run prints the 3 labeled blocks wrapped:, lines:, roundtrip: in source order.
Statements that matter
String wrapped = Base64.getMimeEncoder(20, "\n".getBytes(StandardCharsets.UTF_8))
.encodeToString(payload);
byte[] payload = "The quick brown fox jumps over the lazy dog".repeat(2)
.getBytes(StandardCharsets.UTF_8);
String plain = Base64.getEncoder().encodeToString(payload);
Interactive Tools for This Topic
Base64 Encoder & DecoderEncode text to Base64 and decode Base64 back to text with UTF-8 support. Handles Unicode characters correctly using TextEncoder and TextDecoder APIs.Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Quoted-Printable CodecEncode and decode quoted-printable (RFC 2045) used by email, escaping non-ASCII bytes and wrapping long lines.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.
FAQ
- What does MIME Base64 Wraps Long Lines print when run?
- Execute the whole file; each printed line is prefixed with a label like `wrapped:`, `lines:`, `roundtrip:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.