1

我正在寻找一种quoted-printable在 Java 中编码字符串的方法,就像 php 的原生quoted_printable_encode()函数一样。

我曾尝试使用 JavaMails 的 MimeUtility 库。但我无法让该encode(java.io.OutputStream os, java.lang.String encoding)方法工作,因为它使用 OutputStream 作为输入而不是字符串(我使用该函数getBytes()转换字符串)并输出一些我无法返回到字符串的内容(我是 Java 菜鸟 :)

谁能给我一些提示,告诉我如何编写一个将字符串转换为 OutputStream 并在编码后将结果作为字符串输出的包装器?

4

2 回答 2

4

要使用此MimeUtility方法,您必须创建一个ByteArrayOutputStream将累积写入它的字节,然后您可以恢复它。例如,对字符串进行编码original

ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream encodedOut = MimeUtility.encode(baos, "quoted-printable");
encodedOut.write(original.getBytes());
String encoded = baos.toString();

来自同一个类的encodeText函数可以处理字符串,但它会产生 Q 编码,这与quoted-printable 相似但不完全相同

String encoded = MimeUtility.encodeText(original, null, "Q");
于 2014-02-05T10:49:20.323 回答
1

这对我有帮助

    @Test
public void koi8r() {
    String input = "=5F=F4=ED=5F15=2E05=2E";
    String decode = decode(input, "KOI8-R", "quoted-printable", "KOI8-R");
    Assertions.assertEquals("_ТМ_15.05.", decode);
}

public static String decode(String text, String textEncoding, String encoding, String charset) {
    if (text.length() == 0) {
        return text;
    }

    try {
        byte[] asciiBytes = text.getBytes(textEncoding);
        InputStream decodedStream = MimeUtility.decode(new ByteArrayInputStream(asciiBytes), encoding);
        byte[] tmp = new byte[asciiBytes.length];
        int n = decodedStream.read(tmp);
        byte[] res = new byte[n];
        System.arraycopy(tmp, 0, res, 0, n);
        return new String(res, charset);
    } catch (IOException | MessagingException e) {
        return text;
    }
}
于 2020-05-13T11:35:45.140 回答