Java创建的ZIP文件损坏了

3

我正在使用zeroturnaround的zt-zip,但是当我压缩后尝试打开时,它显示文件已损坏。有什么想法吗?

ZipUtil.pack(new File("C:\\Users\\David"), new File(zipName)); http://pastie.org/3773634

2
只是出于好奇,为什么不使用java.util.zip? - Umer Hayat
请提供一个可重现的测试用例(可以将代码放在pastebin.com或类似网站上)。如果没有测试用例,我们可能无法提供帮助。 - sleske
我已经苦苦挣扎了很长时间。我决定使用这个。 - cheese5505
1
在其他地方发布您的示例代码会降低该问题作为本站独立条目的价值。我经常发现一些相当古老的问题非常有帮助。如果其他网站消失或清除内容,则此问题将变得不完整。我还建议尝试发布一个更小的示例,这将使问题更加集中并更容易找出原因。 - BillRobertson42
1个回答

3
要制作一个Zip文件,您可以直接使用以下Java类:

import java.util.zip.ZipFile;


(请注意保留HTML标记)
// These are the files to include in the ZIP file
String[] filenames = new String[]{"filename1", "filename2"};

// Create a buffer for reading the files
byte[] buf = new byte[1024];

try {
    // Create the ZIP file
    String outFilename = "outfile.zip";
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));

    // Compress the files
    for (int i=0; i<filenames.length; i++) {
        FileInputStream in = new FileInputStream(filenames[i]);

        // Add ZIP entry to output stream.
        out.putNextEntry(new ZipEntry(filenames[i]));

        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        // Complete the entry
        out.closeEntry();
        in.close();
    }

    // Complete the ZIP file
    out.close();
} catch (IOException e) {
}

我以前用过类似的东西,但它总是给我一个已损坏的文件。 - cheese5505
我尝试了一下,它创建了一个ZIP文件,但是没有添加任何内容进去。 - cheese5505
out.putNextEntry(new ZipEntry(filenames[i])); 这个条目将文件添加到zip中,必须使用文件名创建数组,<它应该是完整路径>...这样FileInputStream才能被创建... - Dhruv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接