【问题标题】:Zip file as InputStream then separating each file inside it then converting it to image. In JavaZip 文件作为 InputStream,然后分离其中的每个文件,然后将其转换为图像。在 Java 中
【发布时间】:2012-06-12 22:03:42
【问题描述】:

我得到了一个InputStream 的压缩文件。然后我将其中的每个文件分开。然后我将相同的byte array 传递给pdfbox,它在内部使用Apace pdf box 1.6.0 将其转换为图像。

但是,当我将 byte array 传递给 PDFDocumentReader 时,我得到以下异常-

SEVERE: expected='endstream' actual='' org.apache.pdfbox.io.PushBackInputStream@44c2beb9
java.io.IOException: expected='endstream' actual='' org.apache.pdfbox.io.PushBackInputStream@44c2beb9
at org.apache.pdfbox.pdfparser.BaseParser.parseCOSStream(BaseParser.java:439)
at org.apache.pdfbox.pdfparser.PDFParser.parseObject(PDFParser.java:530)
at org.apache.pdfbox.pdfparser.PDFParser.parse(PDFParser.java:172)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:862)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:829)
at org.dopdf.document.read.pdf.PDFDocumentReader.init(PDFDocumentReader.java:98)

要从 zip 中获取每个文件,我使用以下代码 -

    ZipInputStream zis = new ZipInputStream(aZipFile); // aZipFile is byte array
    ZipEntry entry;
    ArrayList<String> nameOfIgnoredFiles = new ArrayList<String>();
    byte data[] = null;
    while ((entry = zis.getNextEntry()) != null) {
        if (entry.getName().endsWith(".pdf")) {
            int dataSize = (int)entry.getSize();
            data = new byte[dataSize];
            zis.read(data);
            // i use data and pass it to the pdf box.
        } else {
            nameOfIgnoredFiles.add(entry.getName());
        }

我在上面获取的 data 字节数组然后被传递给如下 -

PDFDocumentReader document = new PDFDocumentReader(data); // here i get the error

我做错了什么?你能提出一个解决方案吗?我猜数据字节数组的获取是一个问题。如何做到最好?

【问题讨论】:

    标签: java zip bytearray inputstream pdfbox


    【解决方案1】:

    您假设zis.read(data) 填充了缓冲区。检查 API 文档。不能保证这样做。您还假设大小适合 int,并且项目本身适合内存。这些假设都不成立。

    您当然可以将条目的InputStream 传递给pdfbox API?

    【讨论】:

    • @Juniad (a) 循环读取,直到您获得所有您期望的数据,这对我来说似乎完全显而易见,或者 (b) 使用 DataInputStream.readFully(),或者 (c) 更好建议包含在我上面的最后一句话中。
    • 1.我尝试循环读取它,但是在组合字节数组时遇到了一些问题。 2. DataInputStream 在其构造函数中需要一个InputStream。要通过哪一个? 3.可以通过InputStream但是因为我将文件保存在HBase我必须将它转换为byte array所以之前这样做。
    • @Juniad (a) zis 当然; (b) 如果不需要InputStream,请将zis 复制到ByteArrayOutputStream 并从中获取字节。
    • 我可以将 zis 传递给DataInputStream,但是如何将压缩在我作为流接收的 zip 文件中的文件分开。
    • @Juniad 在每个项目末尾读取输入流时,您将获得 EOF。然后前进到下一个项目并再次阅读。当没有更多项目时,停止。这就是 Javadoc 中的全部内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多