Java:从 URL 读取 pdf 文件到小程序中的字节数组/字节缓冲区 [英] Java: Reading a pdf file from URL into Byte array/ByteBuffer in an applet

查看:37
本文介绍了Java:从 URL 读取 pdf 文件到小程序中的字节数组/字节缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚为什么这段特定的代码对我不起作用.我有一个小程序,它应该读取 .pdf 并使用 pdf-renderer 库显示它,但是由于某种原因,当我读取位于我的服务器上的 .pdf 文件时,它们最终被损坏了.我已经通过再次写回文件对其进行了测试.

I'm trying to figure out why this particular snippet of code isn't working for me. I've got an applet which is supposed to read a .pdf and display it with a pdf-renderer library, but for some reason when I read in the .pdf files which sit on my server, they end up as being corrupt. I've tested it by writing the files back out again.

我尝试在 IE 和 Firefox 中查看小程序,但出现损坏的文件.有趣的是,当我尝试在 Safari(对于 Windows)中查看小程序时,该文件实际上很好!我知道 JVM 可能会有所不同,但我仍然迷失了方向.我已经用 Java 1.5 编译了.JVM 是 1.6.读取文件的片段如下.

I've tried viewing the applet in both IE and Firefox and the corrupt files occur. Funny thing is, when I trying viewing the applet in Safari (for Windows), the file is actually fine! I understand the JVM might be different, but I am still lost. I've compiled in Java 1.5. JVMs are 1.6. The snippet which reads the file is below.

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

我一定是遗漏了什么,我一直在想办法弄清楚.任何帮助是极大的赞赏.谢谢.

I must be missing something, and I've been banging my head trying to figure it out. Any help is greatly appreciated. Thanks.

为了进一步澄清我的情况,我阅读之前和之后的文件的不同之处在于,我阅读后输出的文件比原来的要小得多.打开它们时,它们不被识别为 .pdf 文件.没有抛出我忽略的异常,并且我尝试刷新但无济于事.

To further clarify my situation, the difference in the file before I read then with the snippet and after, is that the ones I output after reading are significantly smaller than they originally are. When opening them, they are not recognized as .pdf files. There are no exceptions being thrown that I ignore, and I have tried flushing to no avail.

此代码段在 Safari 中有效,这意味着文件被完整读取,大小没有差异,并且可以使用任何 .pdf 阅读器打开.在 IE 和 Firefox 中,文件最终总是被损坏,大小始终相同.

This snippet works in Safari, meaning the files are read in it's entirety, with no difference in size, and can be opened with any .pdf reader. In IE and Firefox, the files always end up being corrupted, consistently the same smaller size.

我监视了 len 变量(在读取 59kb 文件时),希望看到在每个循环中读取了多少字节.在 IE 和 Firefox 中,在 18kb 时,in.read(buf) 返回 -1,就好像文件已经结束一样.Safari 不会这样做.

I monitored the len variable (when reading a 59kb file), hoping to see how many bytes get read in at each loop. In IE and Firefox, at 18kb, the in.read(buf) returns a -1 as if the file has ended. Safari does not do this.

我会坚持下去,感谢迄今为止的所有建议.

I'll keep at it, and I appreciate all the suggestions so far.

推荐答案

以防万一这些小的改变有所作为,试试这个:

Just in case these small changes make a difference, try this:

public static ByteBuffer getAsByteArray(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    // Since you get a URLConnection, use it to get the InputStream
    InputStream in = connection.getInputStream();
    // Now that the InputStream is open, get the content length
    int contentLength = connection.getContentLength();

    // To avoid having to resize the array over and over and over as
    // bytes are written to the array, provide an accurate estimate of
    // the ultimate size of the byte array
    ByteArrayOutputStream tmpOut;
    if (contentLength != -1) {
        tmpOut = new ByteArrayOutputStream(contentLength);
    } else {
        tmpOut = new ByteArrayOutputStream(16384); // Pick some appropriate size
    }

    byte[] buf = new byte[512];
    while (true) {
        int len = in.read(buf);
        if (len == -1) {
            break;
        }
        tmpOut.write(buf, 0, len);
    }
    in.close();
    tmpOut.close(); // No effect, but good to do anyway to keep the metaphor alive

    byte[] array = tmpOut.toByteArray();

    //Lines below used to test if file is corrupt
    //FileOutputStream fos = new FileOutputStream("C:\\abc.pdf");
    //fos.write(array);
    //fos.close();

    return ByteBuffer.wrap(array);
}

您忘记关闭 fos,如果您的应用程序仍在运行或突然终止,这可能会导致该文件变短.此外,我添加了创建具有适当初始大小的 ByteArrayOutputStream.(否则 Java 将不得不重复分配一个新数组并复制,分配一个新数组并复制,这很昂贵.)将值 16384 替换为更合适的值.16k 对于 PDF 来说可能很小,但我不知道如何,但平均"大小是您希望下载的大小.

You forgot to close fos which may result in that file being shorter if your application is still running or is abruptly terminated. Also, I added creating the ByteArrayOutputStream with the appropriate initial size. (Otherwise Java will have to repeatedly allocate a new array and copy, allocate a new array and copy, which is expensive.) Replace the value 16384 with a more appropriate value. 16k is probably small for a PDF, but I don't know how but the "average" size is that you expect to download.

由于您使用 toByteArray() 两次(即使其中一个在诊断代码中),我将其分配给一个变量.最后,虽然它应该没有任何区别,但是当您将 整个 数组包装在 ByteBuffer 中时,您只需要提供字节数组本身.提供偏移量 0 和长度是多余的.

Since you use toByteArray() twice (even though one is in diagnostic code), I assigned that to a variable. Finally, although it shouldn't make any difference, when you are wrapping the entire array in a ByteBuffer, you only need to supply the byte array itself. Supplying the offset 0 and the length is redundant.

请注意,如果您以这种方式下载 PDF 文件,请确保您的 JVM 运行时有足够大的堆,这样您就有足够的空间容纳您希望读取的最大文件大小的数倍.您使用的方法将整个文件保存在内存中,只要您负担得起该内存就可以.:)

Note that if you are downloading large PDF files this way, then ensure that your JVM is running with a large enough heap that you have enough room for several times the largest file size you expect to read. The method you're using keeps the whole file in memory, which is OK as long as you can afford that memory. :)

这篇关于Java:从 URL 读取 pdf 文件到小程序中的字节数组/字节缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆