【问题标题】:How to add duplicate file in Zip using ZipEntry如何使用 ZipEntry 在 Zip 中添加重复文件
【发布时间】:2018-07-19 17:55:55
【问题描述】:

我有一个文件列表,该列表可能包含重复的文件名,但这些文件位于具有不同数据的不同位置。现在,当我尝试在 zip 中添加这些文件时,我得到 java.lang.Exception: duplicate entry: File1.xlsx。请建议我如何添加重复的文件名。一种解决方案是,如果我可以将重复文件重命名为 File 、 File_1、File_2 .. 但我不确定如何实现它。请帮忙 !!!如果所有文件名都是唯一的,下面是我的工作代码。

Resource resource = null;
    try (ZipOutputStream zippedOut = new ZipOutputStream(response.getOutputStream())) {

        for (String file : fileNames) {

             resource = new FileSystemResource(file);

             if(!resource.exists() && resource != null) {

            ZipEntry e = new ZipEntry(resource.getFilename());
            //Configure the zip entry, the properties of the file
        e.setSize(resource.contentLength());
            e.setTime(System.currentTimeMillis());
            // etc.
        zippedOut.putNextEntry(e);
            //And the content of the resource:
            StreamUtils.copy(resource.getInputStream(), zippedOut);
            zippedOut.closeEntry();

             }
        }
        //zippedOut.close();
        zippedOut.finish();

    return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=download.zip").body(zippedOut);
    } catch (Exception e) {
        throw new Exception(e.getMessage()); 
    }

【问题讨论】:

  • 仅供参考:if(resource.exists() && resource != null) 中的空检查毫无意义。如果resource 为空,则尝试调用exists() 将抛出NullPointerException 您进行空检查之前。任何好的 IDE 都应该警告你这一点,例如Eclipse 会说:“冗余空检查:变量resource 在这个位置不能为空”
  • @Andreas 是的,这是我的错,我必须使用!存在的运算符。我可以改变它。但这里的实际问题是如何在 ZipEntry 中添加重复的文件名,如果你能帮忙的话会很好。
  • 这是您需要的吗? stackoverflow.com/questions/1399126/…
  • @PavelMolchanov 感谢分享,但这不是我实际上在寻找您分享的链接,主要适用于此处的目录我向我们提出如何插入同名文件

标签: java spring spring-restcontroller


【解决方案1】:

一种解决方案是,如果我可以将重复文件重命名为 FileFile_1File_2,......但我不确定如何实现它。

构建一个Set 的名称,并在需要时附加一个数字以使名称唯一,例如

Set<String> names = new HashSet<>();
for (String file : fileNames) {

    // ...

    String name = resource.getFilename();
    String originalName = name;
    for (int i = 1; ! names.add(name); i++)
        name = originalName + "_" + i;
    ZipEntry e = new ZipEntry(name);

    // ...

}

代码依赖于 add() 返回 false 如果名称已经在 Set 中,即如果名称是重复的。

即使给定的名称已经编号,这也会起作用,例如这是给定传入名称顺序的映射名称示例:

foo_2
foo
foo   -> foo_1
foo   -> foo_3        foo_2 was skipped
foo   -> foo_4
foo_1 -> foo_1_1      number appended to make unique

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 2018-07-27
    相关资源
    最近更新 更多