【发布时间】: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 中添加重复的文件名,如果你能帮忙的话会很好。
-
@PavelMolchanov 感谢分享,但这不是我实际上在寻找您分享的链接,主要适用于此处的目录我向我们提出如何插入同名文件
标签: java spring spring-restcontroller