3

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

(当我使用我的操作系统工具制作一个 zip 文件然后将其读回时,大小是正确的,所以我认为问题ZipOutputStream出在ZipInputStream.

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

我究竟做错了什么?谢谢。

这是代码:

// 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...
4

2 回答 2

1

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

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

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

试试看,像这样:

        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();
于 2012-11-05T08:18:05.607 回答
0

似乎 entry.getSize() 根本不可靠:Why ZipInputStream can't read the output of ZipOutputStream?

上面的帖子提供了一个合适的解决方法。

于 2012-11-05T18:09:06.273 回答