ZipOutputStream,大小= -1

时间:2012-11-05 08:07:07

标签: java io zipoutputstream

我正在使用非常标准的代码创建一个ZipOutputStream的zip文件。出于某种原因,当我以ZipInputStream ZipEntry size=-1的方式将其读回时ZipEntry。文件名正确存储在ZipOutputStream

(当我使用我的操作系统工具制作一个zip文件然后再读回来时,大小是正确的,所以我认为问题出在ZipInputStream而不是// export zip file String file = "/Users/me/Desktop/test.jpg"; FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(file+".zip"); ZipOutputStream zos = new ZipOutputStream(fos); zos.putNextEntry(new ZipEntry("test.jpg")); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fis.read(buffer)) > 0) { zos.write(buffer, 0, bytesRead); } zos.closeEntry(); zos.close(); fis.close(); // import same file String file2 = "/Users/me/Desktop/test.jpg.zip"; FileInputStream fis2 = new FileInputStream(file2); ZipInputStream zis = new ZipInputStream(fis2); ZipEntry entry = zis.getNextEntry(); // here: entry.getSize() = -1, zip.buf is an array of zeros... // but if I unzip the file on my OS I see that the original file has been zipped... )。

上下文是一个Spring MVC控制器。

我做错了什么? 感谢。

以下是代码:

{{1}}

2 个答案:

答案 0 :(得分:1)

您必须从流中获取下一个条目,如下例所示:

http://www.roseindia.net/tutorial/java/corejava/zip/zipentry.html

当您手动设置大小时,它肯定会给您一个结果,就像您显示“64527”一样。 你最好看看zip示例。他们会给你一个清晰的形象。 另外:Create Java-Zip-Archive from existing OutputStream

尝试一下这样的事情:

        String inputFileName = "test.txt";
        String zipFileName = "compressed.zip";

        //Create input and output streams
        FileInputStream inStream = new FileInputStream(inputFileName);
        ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName));

        // Add a zip entry to the output stream
        outStream.putNextEntry(new ZipEntry(inputFileName));

        byte[] buffer = new byte[1024];
        int bytesRead;

        //Each chunk of data read from the input stream 
        //is written to the output stream
        while ((bytesRead = inStream.read(buffer)) > 0) {
            outStream.write(buffer, 0, bytesRead);
        }

        //Close zip entry and file streams
        outStream.closeEntry();

        outStream.close();
        inStream.close();

答案 1 :(得分:0)

看来entry.getSize()简直不可靠:Why ZipInputStream can't read the output of ZipOutputStream?

上述帖子提供了合适的解决方法。