如何使用ZipEntry

时间:2018-07-19 17:55:56

标签: java spring spring-restcontroller

我有一个文件列表,该列表可能包含重复的文件名,但这些文件位于具有不同数据的不同位置。现在,当我尝试以zip格式添加这些文件时,我得到 java.lang.Exception:重复项:File1.xlsx 。请建议我如何添加重复的文件名。一种解决方案是,如果可以将dulpicate文件重命名为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()); 
    }

1 个答案:

答案 0 :(得分:0)

  

一种解决方案是,如果我可以将重复文件重命名为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
相关问题