/** * 获取压缩文件解压后的内容和文件类型 * * @param inputStream 压缩文件流 * @return * @author 许伟强51189 * @date 2022/4/1 17:10 * @throws XthIncidentException 发生异常时 */ private static ZipFileResult getZipFileResult(InputStream inputStream) throws Exception { File dir = null; byte[] contentByte = null; String fileType = ""; try { // file对象临时解压后的文件对象 String tmpDirName = "xth_" + UUID.randomUUID(); final File tmpUnZipFile = new File("/tmp/" + tmpDirName); log.info("tmpUnZipFile:{}", tmpUnZipFile); // 解压 dir = ZipUtil.unzip(inputStream, tmpUnZipFile, StandardCharsets.UTF_8); File targetFile = null; if (dir.isDirectory()) { final File[] files = dir.listFiles(); if (files != null && files.length == 1) { targetFile = files[0]; log.info("targetFile:{}", targetFile); if (targetFile.length() > 1024 * 1024 * 20) { throw new Exception("unzip file target out size limit "); } log.info("targetFile length:{}", targetFile.length()); String fileName = targetFile.getName(); log.info("targetFile getName :{}", fileName); fileType = fileName.substring(fileName.lastIndexOf(".") + 1); log.info("fileType:{}", fileType); } } if (targetFile == null) { throw new Exception("unzip file target is null"); } contentByte = FileUtils.readFileToByteArray(targetFile); } catch (UtilException | IOException e) { throw new Exception("unzip file error " + e.getMessage()); } finally { if (dir != null) { try { FileUtils.deleteDirectory(dir); } catch (IOException e) { log.error("del tmp file error:{} ", e.getMessage()); } } } log.info("contentByte:{}", contentByte); log.info("contentByte:{}", contentByte.toString()); return ZipFileResult.builder().fileType(fileType).contentByte(contentByte).build(); }
使用到的包有:
cn.hutool.core.util.ZipUtil;
org.apache.commons.io.FileUtils
一个好用的工具库
https://apidoc.gitee.com/loolly/hutool/cn/hutool/core/util/package-summary.html
https://commons.apache.org/proper/commons-io/