【问题标题】:Unable to unzip zip file created with java无法解压缩使用 java 创建的 zip 文件
【发布时间】:2014-01-07 13:41:24
【问题描述】:

我有一份来自不同位置的文件列表。我使用以下代码创建了一个 zip 文件,该代码可以正常工作。但是,当我尝试使用 Extract All 在 Windows 中解压缩文件时,它无法看到找不到任何字节,但是如果我使用 Windows 资源管理器双击压缩文件本身,我可以看到文件和单个文件可以打开并包含正确的数据

       ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
        for (File next : files)
        {
            ZipEntry zipEntry = new ZipEntry(next.getName());
            zos.putNextEntry(zipEntry);
            FileInputStream in = new FileInputStream(next);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0)
            {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            in.close();
        }
        zos.close();

【问题讨论】:

    标签: java zip winzip


    【解决方案1】:

    这可能相关也可能不相关,但我发现使用固定字节长度会导致换行符丢失。

    这可能会有所帮助:

    final byte[] newLine = System.getProperty(
            "line.separator").getBytes("UTF-8");
    
    while ((line = in.readLine()) != null) 
            final byte[] buffer = line.getBytes("UTF-8");
            out.write(buffer, 0, buffer.length);
            out.write(newLine, 0, newLine.length);
    }
    

    【讨论】:

      最近更新 更多