public String fileToZip(String simpleLogId) {
// 这里根据数据库存放的文件信息找到所有文件
List<FilePath> files = filePathMapper.selectByInstallId(simpleLogId);
String url = "";
if (files!= null && files.size() > 0) {
List<String> filePaths = files.stream().map(FilePath::getFilePath).collect(Collectors.toList());
// 这里可配置网络路径
url = parameter.getFileUrl() + "zip/" + simpleLogId + ".zip";
try {
// 创建压缩文件
FileOutputStream fos = new FileOutputStream("file/zip/" + simpleLogId + ".zip");
ZipOutputStream zipOut = new ZipOutputStream(fos);
// 循环添加每个文件到压缩包
for (String filePath : filePaths) {
filePath = "file/"+ filePath;
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
// 添加一个新的ZipEntry到压缩包中
ZipEntry zipEntry = new ZipEntry(filePath);
zipOut.putNextEntry(zipEntry);
// 将文件内容写入压缩包中
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
// 关闭当前ZipEntry并释放资源
zipOut.closeEntry();
fis.close();
}
// 关闭ZipOutputStream并释放资源
zipOut.close();
} catch (Exception e) {
throw new ResponseCommonException(ErrorMsg.FILE_CONVERSION_FAILED);
}
}
// 返回路径
return url;
}
Java将文件打包为压缩包zip
最新推荐文章于 2023-08-17 10:14:53 发布