← 中文资源

简体中文版本

MIME Base64 长行折行

用 Base64.getMimeEncoder 按固定宽度折行编码长载荷,再用 MIME 解码器忽略换行还原原始字节;普通编码器不折行。

阅读英文原文

实现说明

整个示例围绕类 Main和函数 main组织。

使用要点

  • 每一步打印都带着自己的标签:wrapped:、lines:、roundtrip:。

常见问题

运行「MIME Base64 长行折行」会打印什么?

运行文件本身,wrapped:、lines:、roundtrip: 这些前缀各对应一段演示逻辑。

核心语句

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);

代码示例

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"));
    }
}