我有一个普通的pdf文件 A.pdf ,第三方以base64对该文件进行编码,并将其作为长字符串在网络服务中发送给我(我无法控制第三方)。
我的问题是,当我使用 java org.apache.commons.codec.binary.Base64 解码字符串并将输出正确到名为 B.pdf 的文件时
我希望 B.pdf 与 A.pdf 相同,但 B.pdf 结果与 A.pdf 略有不同。因此,Acrobat 无法将 B.pdf 识别为有效的 pdf。
base64 是否有不同类型的编码\字符集机制?我可以检测我收到的字符串是如何编码的,以便 B.pdf=A.pdf 吗?
编辑-这是我想要解码的文件,解码后它应该以 pdf 格式打开
我的编码文件 http://wikisend.com/download/321380/base64.819
这是在记事本++中打开的文件的标题
**A.pdf**
%PDF-1.4
%±²³´
%Created by Wnv/EP PDF Tools v6.1
1 0 obj
<<
/PageMode /UseNone
/ViewerPreferences 2 0 R
/Type /Catalog
**B.pdf**
%PDF-1.4
%±²³´
%Created by Wnv/EP PDF Tools v6.1
1 0! bj
<<
/PageMode /UseNone
/ViewerPreferences 2 0 R
/]
pe /Catalog
这就是我解码字符串的方式
private static void decodeStringToFile(String encodedInputStr,
String outputFileName) throws IOException {
BufferedReader in = null;
BufferedOutputStream out = null;
try {
in = new BufferedReader(new StringReader(encodedInputStr));
out = new BufferedOutputStream(new FileOutputStream(outputFileName));
decodeStream(in, out);
out.flush();
} finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
}
private static void decodeStream(BufferedReader in, OutputStream out)
throws IOException {
while (true) {
String s = in.readLine();
if (s == null)
break;
//System.out.println(s);
byte[] buf = Base64.decodeBase64(s);
out.write(buf);
}
}
您正在通过逐行工作来破坏解码。Base64 http://en.wikipedia.org/wiki/Base64解码器只是忽略空格,这意味着原始内容中的一个字节很可能被分成两个 Base64 文本行。您应该将所有行连接在一起并一次性解码文件。
更喜欢使用byte[]
而不是String
当向Base64
类方法。String
意味着字符集编码,这可能不会达到您想要的效果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)