Hutool文档
https://www.hutool.cn/docs/#/core/IO/%E6%96%87%E4%BB%B6%E5%B7%A5%E5%85%B7%E7%B1%BB-FileUtil
https://apidoc.gitee.com/loolly/hutool/
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.2.0</version>
</dependency>
/**
* 下载zip压缩包
* @param response
* @param id
* @throws IOException
*/
@GetMapping("/download/zip")
public void downloadClientZipFile(HttpServletResponse response, @RequestParam("id") Integer id) throws IOException {
try {
companyService.downloadClientZipFile(response,id);
} catch (Exception e) {
e.printStackTrace();
logger.error("",e);
}
}
void File(HttpServletResponse response, @RequestParam("id") Integer id) throws Exception;
@Override
public void File(HttpServletResponse response, Integer id) throws Exception {
Company company = companyMapper.selectById(id);
String filename = company.getCopName() + ".zip";
response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
//下载显示的文件名,解决中文名称乱码问题
String downloadFielName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
response.setHeader("Content-Disposition", "attachment; filename=" + downloadFielName);
ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
boolean fileExist = FileUtil.exist( File.separator + "opt" + File.separator + "File");
if (!fileExist){
logger.error("File文件不存在");
return;
}
InputStream inputStream = null;
// wiondws环境项目在D盘任意位置默认搜索项目所在磁盘 D:\opt\File 此方法兼用wiondws和linux (linux环境 \opt\File)
//遍历目录以及子目录中的所有文件
List<File> files = FileUtil.loopFiles(File.separator + "opt" + File.separator + "File");
for (File file : files) {
inputStream = FileUtil.getInputStream(file);
//压缩包路径 (去除opt目录保留File目录)
int FileIndex = file.getPath().indexOf("File");
String createZipPath = file.getPath().substring(FileIndex);
//创建压缩包路径
zipOutputStream.putNextEntry(new ZipEntry(company.getCode() +"/"+ createZipPath));
//修改properties
if("xx.properties".equals(file.getName())){
String read = IoUtil.read(inputStream, "UTF-8");
read = read.replace("xx=", "xx="+company.getCode())
inputStream = IoUtil.toStream(read, "UTF-8");
}
//修改xml内容
if ("xx.xml".equals(file.getName())) {
String read = IoUtil.read(inputStream, "UTF-8");
read = read.replace("x", "xxx")
inputStream = IoUtil.toStream(read, "UTF-8");
}
IoUtil.copy(inputStream,zipOutputStream);
zipOutputStream.flush();
}
zipOutputStream.closeEntry();
zipOutputStream.close();
}