/** * 獲取壓縮文件解壓后的內容和文件類型 * * @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/