java zip 存档损坏

标签 java zip

我创建的存档有问题 - 尝试解压缩 Windows 时显示存在错误。是代码的问题吗?

File dir = new File("M:\\SPOT/netbeanstest/TEST/PDF");
    String archiveName = "test.zip";

    byte[] buf = new byte[1024];
    try {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
                archiveName));

        for (String s : dir.list()) {
            File toCompress = new File(dir, s);
            FileInputStream fis = new FileInputStream(toCompress);

            zos.putNextEntry(new ZipEntry(s));
            int len;
            while((len = fis.read(buf))>0){
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            fis.close();
        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

最佳答案

我会写下我的评论作为答案,因为它解决了问题。

所有流( InputStreamOutputStream )应以其 close() 关闭方法来确保数据已写出并且没有留下任何打开的处理程序。

最好在finally block 中执行此操作,如下所示:

ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(archiveName));

try {
    for (String s : dir.list()) {
        File toCompress = new File(dir, s);
        FileInputStream fis = new FileInputStream(toCompress);

        try {
            zos.putNextEntry(new ZipEntry(s));
            int len;

            while((len = fis.read(buf))>0){
                zos.write(buf, 0, len);
            }
            zos.closeEntry();

        } finally {
            fis.close();
        }
    }
} finally {
    zos.close();
}

关于java zip 存档损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11323544/

相关文章:

java - 错误: “Syntax error on token ” ;“, , expected”

zip - .doc 格式如何工作?

macos - 如何在 Mac OS X 上为 zip 文件提供密码

java - 每秒上传进度 - Android

java - 随机 java.lang.IllegalStateException : Cannot forward after response has been committed

java - Dcm4Che - 从 pacs 获取图像

java - 如何使用 webdriver 和 java 查找日历表中的链接?

python - 获取远程 zip 文件并列出其中的文件

java - tomcat 7访问映射驱动器

java - 使用 java.util.zip 构建有效的 epub