繁体   English   中英

Java:在带引号的可打印中编码字符串

[英]Java: Encode String in quoted-printable

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

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

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

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

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

来自同一个类的encodeText函数可以处理字符串,但它产生 Q-encoding,它类似于encodeText -printable 但不完全相同

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

这就是帮助我的原因

    @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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM