我正在寻找一种方法来在Java中对字符串进行quoted-printable
编码,就像php的本机quoted_printable_encode()
函数一样。
我尝试过使用JavaMails的MimeUtility库。但是我不能让encode(java.io.OutputStream os, java.lang.String encoding)
方法工作,因为它接受OutputStream而不是字符串作为输入(我使用getBytes()
函数来转换字符串),并输出一些我无法返回到字符串的东西(我是Java noob :)
谁能给我一些技巧,告诉我如何编写一个包装器,将一个字符串转换成一个OutputStream,并在编码后将结果作为字符串输出?
发布于 2014-02-05 18:49:20
要使用这个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");
发布于 2020-05-13 19:35:45
这对我有帮助。
@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;
}
}
https://stackoverflow.com/questions/21574745
复制相似问题