Java - 创建包含重复条目的ZIP文件

时间:2016-10-10 12:37:57

标签: java zip

我想创建一个zip,它存储两个名称相同的不同文件,但由于

,我无法使用java.util.zip.ZipOutputStream
  

java.util.zip.ZipException:重复条目:

异常。我知道这是可能的,但我需要建议我可以用于此目的的库。谢谢!

使用以下代码更新代码

File zipFile = new File("C:\\Users\\user\\Desktop\\old.zip");
File outFile = new File("C:\\Users\\user\\Desktop\\new.zip");
if(!outFile.exists()) {
    outFile.getParentFile().mkdirs();
    outFile.createNewFile();
}

byte[] buf = new byte[1024];
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFile));

ZipEntry entry = zin.getNextEntry();
while (entry != null) {
    String name = entry.getName();
    out.putNextEntry(new ZipEntry(name));
    int len;
    while ((len = zin.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    entry = zin.getNextEntry();

    if("file".equals(name)) {
        File fakeFile = new File("C:\\Users\\user\\Desktop\\file");
        InputStream in = new FileInputStream(fakeFile);
        out.putNextEntry(new ZipEntry("file"));
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
} 
zin.close();
out.close();

2 个答案:

答案 0 :(得分:2)

我能够通过反射api绕过限制:

Field namesField = ZipOutputStream.getDeclaredField("names");
namesField.setAccessible(true);
HashSet<String> names = (HashSet<String>) namesField.get(out);

在每次names电话

后清除putNextEntry

答案 1 :(得分:0)

try (FileOutputStream fos = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos)) {

        HashSet<String> names = new HashSet<String>();
        for (String filePath : fileList) {
            if(names.add(filePath))
            {
            String name = filePath.substring(directory.getAbsolutePath()
                    .length() + 1, filePath.length());
            ZipEntry zipEntry = new ZipEntry(name);

            zos.putNextEntry(zipEntry);
            try (FileInputStream fis = new FileInputStream(filePath)) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) >= 0) {
                    zos.write(buffer, 0, length);
                }

            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception();
            }
            zos.closeEntry();
            }

        }
        names.clear();
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception();
    }

通过使用HashSet解决了我的zip重复条目问题

相关问题