开发者

Java处理压缩文件的步骤详解

目录
  • 背景
  • 第一步:编写代码
    • 1.1 请求层
    • 1.2 业务处理层
    • 1.3 新增配置
  • 第二步:解压缩处理
    • 2.1 引入依赖
    • 2.2 解压缩工具类
  • 总结

    背景

    在项目出现上传文件,其中文件包含压缩包,并对压缩包的内容进行解析保存。

    第一步:编写代码

    1.1 请求层

    我们用倒叙的方式来写。先写 ZipController

    	php@Autowired
        private ZipService zipService;
    
        /**
         * 上传二维码文件
         * @param qrCodeFile 二维码文件
         * @return 返回上传的结果
         */
        @ApiOperation(value = "上传二维码文件")
        @PostMapping("/uploadQrCodeFile")
        public Result uploadQrCodeFile(@RequestParam("file") MultipartFile qrCodeFile) throws Exception {
            zipService.uploadQrCodeFile(qrCodeFile);
            return Result.sendSuccess("上传成功");
        }
    
    

    1.2 业务处理层

    接着就是写 Service

    @Service
    public class ZipService {
    
    
        private static final Logger logger= LoggerFactory.getLogger(ZipService.class);
    
    
        public void uploadQrCodeFile(MultipartFile multipartFile)throws Exception {
            if (multipartFiphple.getSize() == 0
                    || multipartFile.getOriginalFilename() == null
                    || (multipartFile.getOriginalFilename() != null
                    && !multipartFile.getOriginalFilename().contains("."))) {
                ExceptionCast.cast(Result.sendFailure("文件格式不正确或文件为空!"));
            }
            // 1.先下载文件到本地
            String originalFilename = multipartFile.getOriginalFilename();
            String destPath = System.getProperty("user.dir") + File.separator + "qrCodeFile";
            FileUtil.writeFromStream(
                    multipartFile.getInputStream(), new File(destPath + File.separator + originalFilename));
    
            // 2.解压文件
            unzipAndSaveFileInfo(originalFilename, destPath);
            // 3.备份压缩文件,删除解压的目录
            FileUtils.copyFile(
                    new File(destPath + File.separator + originalFilename),
                    new File(destPath + File.separator + "backup" + File.separator + originalFilename));
            // 删除原来的上传的临时压缩包
            FileUtils.deleteQuietly(new File(destPath + File.separator + originalFilename));
            logger.info("文件上传成功,文件名为:{}", originalFilename);
    
    
        }
    
        /**
         * 解压和保存文件信息
         *
         * @param originalFilename 源文件名称
         * @param destPath         目标路径
         */
        private void unzipAndSaveFileInfo(String originalFilename, String destPath) throws IOException {
            if (StringUtils.isEmpty(originalFilename) || !originalFilename.co编程客栈ntains(".")) {
                ExceptionCast.cast(Result.sendFailure("文件名错误!"));
            }
            // 压缩
            ZipUtil.unzip(
                    new File(destPath + File.separator + originalFilename),
                    new File(destPath),
                    Charset.forName("GBK"));
            // 遍历文件信息
            String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            File[] files = FileUtil.ls(destPath + File.separator + fileName);
            if (files.length == 0) {
                ExceptionCast.cast(Result.sendFailure("上传文件为空!"));
            }
            String targetPath = destPath + File.separator + "images";
            for (File file : files) {
                // 复制文件到指定目录
                String saveFileName =
                        System.currentTimeMillis() + new SecureRandom().nextInt(100) + file.getName();
                FileUtils.copyFile(file, new File(targetPath + File.separator + saveFileName));
                logger.info("文件名称:"+file.getName());
                logger.info("文件所在目录地址:"+saveFileName);
                logger.info("文件所在目录地址:"+targetPath + File.separator + saveFileName);
            }
        }
    }
    

    1.3 新增配置

    因spring boot有默认上传文件大小限制,故需配置文件大小。在 application.properties 中添加 upload 的配置

    #### upload begin  ###
    spring.servlet.multipart.enabled=true
    spring.servlet.multipart.max-request-size=10MB
    spring.servlet.multipart.max-file-size=10MB
    #### upload end  ###
    

    第二步:解压缩处理

    2.1 引入依赖

    引入 Apache 解压 / 压缩 工具类处理,解压 tar.gz 文件

    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-compress -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-compress</artifactId>
        <version>1.20</version>
    </dependency>
    

    2.2 解压缩工具类

    • 将 tar.gz 转换为 tar
    • 解压 tar
    import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
    import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
    import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
    import org.apache.commons.compress.utils.IOUtils;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.Element;
    import org.dom4j.io.SAXReader;
    import org.springframework.stereotype.Service;
    import org.springframework.util.CollectionUtils;
    import org.XML.sax.EntityResolver;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    
    
           // tar.gz 文件路径
            String sourcePath = "D:\\daleyzou.tar.gz";
            // 要解压到的目录
        android    String extractPath = "D:\\test\\daleyzou";
            File sourceFile = new File(sourcePath);
            // decompressing *.tar.gz files to tar
            TarArchiveInputStream fin = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(sourceFile)));
            File extraceFolder = new File(extractPath);
            TarArchiveEntry entry;
            // 将 tar 文件解压到 extractPath 目录下
            while ((entry = fin.getNextTarEntry()) != null) {
                if (entry.isDirectory()) {
                    continue;
                }
                File curfile = new File(extraceFolder, entry.getName());
                File parent = curfile.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                }
                // 将文件写出EaRohMNNYG到解压的目录
                IOUtils.copy(fin, new FileOutputStream(curfile));
            }
    

    总结

    到此这篇关于Java处理压缩文件的步骤详解的文章就介绍到这了,更多相关Java处理压缩文件内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新开发

    开发排行榜