java獲取壓縮文件的文件內容和文件后綴名


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM