【发布时间】:2012-02-17 22:47:50
【问题描述】:
我有一个普通的 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格式打开
这是在记事本++中打开的文件的标题
**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);
}
}
【问题讨论】:
-
我过去在使用
Strings 时也看到过类似的结果。您可以尝试使用原始的byte[]s 来代替,看看它是否有所作为。 -
您还需要显示执行 base64 编码的代码块。
-
我只从第三方获取字符串。我应该使用 String.getBytes(charset) 将字符串转换为字节吗?我怎么知道要使用什么字符集?
-
我没有编码代码,正如我所说,它来自第三方,我无法使用()它甚至在 java 中也没有。
标签: java base64 encode java-io