用户上传压缩包BIZ文件,后台进行解析并进行数据处理,在此记录核心代码以便后续使用
/**
* 将zip包解并进行解析
*
* @param zipInputStream zip输入流
* @param toPath 需要解压的目标目录
* @param info info
* @throws IOException IOException
*/
private List<BizFile> unzip(InputStream zipInputStream, String toPath, BizIoMasterDto info) throws Exception {
Path destDir = Paths.get(toPath);
List<BizFile> fileNames = new ArrayList<>();
List<IitImportAnalyseDto> errorList = new ArrayList<>();
if (!Files.exists(destDir)) {
Files.createDirectories(destDir);
}
byte[] buffer = new byte[1024];
logger.info("sun.jnu.encoding:{}", Charset.forName(System.getProperty(Constant.WINDOWS_ENCODING)));
ZipInputStream zis = new ZipInputStream(zipInputStream, Charset.forName(System.getProperty(Constant.WINDOWS_ENCODING)));
ZipEntry zipEntry = zis.getNextEntry();
if (zipEntry == null) {
IitImportAnalyseDto errorDto = new IitImportAnalyseDto();
errorDto.setFileName(info.getSrcFileName());
errorDto.setErrorMsg(this.errorMsgMap.get("parsing_error").getI18nvalue());
errorList.add(errorDto);
}
while (zipEntry != null) {
Path destFile = destDir.resolve(zipEntry.getName());
if (!zipEntry.isDirectory()) {
BizFile toSave = new BizFile();
String fileName = destFile.getFileName().toString();
// 校验
String errorMsg = this.validateFile(fileName);
// 校验未通过
if (StringUtils.isNotBlank(errorMsg)) {
IitImportAnalyseDto errorDto = new IitImportAnalyseDto();
errorDto.setFileName(fileName);
errorDto.setErrorMsg(errorMsg);
errorList.add(errorDto);
} else {
// 文件拓展名
String fileSuffix = this.extName(fileName);
String uuid = UUID.randomUUID().toString();
toSave.setUuid(uuid);
toSave.setOldName(fileName);
toSave.setNewName(uuid + "." + fileSuffix);
toSave.setSuffix(fileSuffix);
fileNames.add(toSave);
try (FileOutputStream fos = new FileOutputStream(new File(toPath + File.separator + toSave.getNewName()))) {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
}
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
info.setImportErrorList(errorList);
return fileNames;
}