我试图找出为什么这个特定的代码片段对我不起作用.我有一个applet,应该读取.pdf并用pdf-renderer库显示它,但出于某种原因,当我读入位于我服务器上的.pdf文件时,它们最终会被破坏.我已经通过再次写出文件来测试它.
我尝试在IE和Firefox中查看applet,并且发生了损坏的文件.有趣的是,当我尝试在Safari(对于Windows)中查看applet时,该文件实际上很好!我理解JVM可能会有所不同,但我仍然迷失方向.我已经用Java 1.5编译了.JVM是1.6.读取文件的代码段如下.
public static ByteBuffer getAsByteArray(URL url) throws IOException {
ByteArrayOutputStream tmpOut = new ByteArrayOutputStream();
URLConnection connection = url.openConnection();
int contentLength = connection.getContentLength();
InputStream in = url.openStream();
byte[] buf = new byte[512];
int len;
while (true) {
len = in.read(buf);
if (len == -1) {
break;
}
tmpOut.write(buf, 0, len);
}
tmpOut.close();
ByteBuffer bb = ByteBuffer.wrap(tmpOut.toByteArray(), 0,
tmpOut.size());
//Lines below used to test if file is corrupt
//FileOutputStream fos = new FileOutputStream("C:\\abc.pdf");
//fos.write(tmpOut.toByteArray());
return bb;
}
Run Code Online (Sandbox Code Playgroud)
我一定是在遗漏一些东西,而且我一直在试图解决这个问题.任何帮助是极大的赞赏.谢谢.
编辑: 为了进一步说明我的情况,我在阅读之后使用片段和之后的文件中的差异是,我在阅读后输出的内容明显小于原来的内容.打开它们时,它们不会被识别为.pdf文件.没有任何例外被抛出我忽略,我试着冲洗无济于事. …