如何使用 ZipEntry 在 Zip 中添加重复文件

abh*_*han 2 java spring spring-restcontroller

我有一个文件列表,该列表可能包含重复的文件名,但这些文件驻留在具有不同数据的不同位置。现在,当我尝试在 zip 中添加这些文件时,我收到java.lang.Exception:重复条目: 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()); 
    }
Run Code Online (Sandbox Code Playgroud)

And*_*eas 6

一种解决方案是,如果我可以将重复文件重命名为File, File_1, File_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);

    // ...

}
Run Code Online (Sandbox Code Playgroud)

该代码依赖于add()返回false名称是否已在 中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);

    // ...

}
Run Code Online (Sandbox Code Playgroud)