首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用ZipEntry在Zip中添加重复文件

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

Stack Overflow用户
提问于 2018-07-19 17:55:55
回答 2查看 2.4K关注 0票数 2

我有一个文件列表,该列表可能包含重复的文件名,但这些文件驻留在不同的位置,具有不同的数据。现在,当我试图在zip中添加这些文件时,我得到的是java.lang.Exception::File1.xlsx。请建议我如何添加重复的文件名。一种解决方案是,如果我可以将该文件重命名为文件,File_1,File_2。但我不知道如何才能做到这一点。救命啊!下面是我的工作代码,如果所有的文件名都是唯一的。

代码语言:javascript
运行
复制
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()); 
    }
EN

Stack Overflow用户

发布于 2022-10-11 07:50:10

此解决方案复制windows使用的索引样式"filename (n).doc",同时尊重文件扩展名

代码语言:javascript
运行
复制
Map<String, Integer> nombresRepeticiones = new HashMap<String, Integer>();
for(FileDTO file : files) {
    String filename = file.getNombre();
    if (nombresRepeticiones.containsKey(filename)) {
                    
        int numeroRepeticiones = nombresRepeticiones.get(filename) + 1;                     
        String base = FilenameUtils.removeExtension(filename);
        String extension = FilenameUtils.getExtension(filename);
                    
        filename = base + " (" + numeroRepeticiones + ")"; 
                    
        if (extension != null && !extension.isEmpty()) {
            filename = filename + "." + extension;
        }
                    
        nombresRepeticiones.put(file.getNombre(), numeroRepeticiones);                      
    }
    else {
        nombresRepeticiones.put(filename, 0);
    }
                
    ZipEntry ze = new ZipEntry(filename);
    zos.putNextEntry(ze);                                
    zos.write(IOUtils.toByteArray(file.getContenido().getInputStream()));
    zos.closeEntry();
}
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51429107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档