我有一个文件列表,该列表可能包含重复的文件名,但这些文件驻留在不同的位置,具有不同的数据。现在,当我试图在zip中添加这些文件时,我得到的是java.lang.Exception::File1.xlsx。请建议我如何添加重复的文件名。一种解决方案是,如果我可以将该文件重命名为文件,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());
}
发布于 2022-10-11 07:50:10
此解决方案复制windows使用的索引样式"filename (n).doc",同时尊重文件扩展名
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();
}
https://stackoverflow.com/questions/51429107
复制相似问题