ZIP文件解压

zip文件解压

    /*
     * 文件解压
     */
    public Map<String, FileModel> unzip(MultipartFile file) {
        if (file == null)
            return null;
        // 判断文件是否为zip文件
        String filename = file.getOriginalFilename();
        if (!filename.endsWith("zip")) {
            logger.info("传入文件格式不是zip文件" + filename);
            new Exception("传入文件格式错误" + filename);
        }
        Map<String, FileModel> fileModelList = new HashMap<>();
        String zipFileName = null;
        // 对文件进行解析
        try {
            ZipInputStream zipInputStream = new ZipInputStream(file.getInputStream(), Charset.forName("GBK"));
            BufferedInputStream bs = new BufferedInputStream(zipInputStream);
            ZipEntry zipEntry;
            byte[] bytes = null;
            while ((zipEntry = zipInputStream.getNextEntry()) != null) { // 获取zip包中的每一个zip file entry
                zipFileName = zipEntry.getName();
                Assert.notNull(zipFileName, "压缩文件中子文件的名字格式不正确");
                FileModel fileModel = new FileModel();
                fileModel.setFileName(zipFileName);
                bytes = new byte[(int) zipEntry.getSize()];
                bs.read(bytes, 0, (int) zipEntry.getSize());
                InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
                fileModel.setMultipartFile(new DataTransMultipartFile(zipFileName, zipFileName, "", byteArrayInputStream));
                fileModel.setFileInputstream(byteArrayInputStream);
                fileModelList.put(zipFileName.split("\\.")[0], fileModel);
            }
        } catch (Exception e) {
            logger.error(e);
            new Exception("读取部署包文件内容失败,请确认部署包格式正确:" + zipFileName);
        }
        return fileModelList;
    }

 

posted @ 2020-04-28 10:56  怡安  阅读(503)  评论(0编辑  收藏  举报