Java:在quoted-printable中编码String

时间:2014-02-05 10:33:36

标签: java javamail mime quoted-printable

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

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

有人可以给我一些提示,告诉我如何编写一个将String转换为OutputStream的包装器,并在编码后将结果作为String输出吗?

2 个答案:

答案 0 :(得分: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编码,即similar to quoted-printable but not quite the same

String encoded = MimeUtility.encodeText(original, null, "Q");

答案 1 :(得分: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;
    }
}
相关问题