@


前言

请各大网友尊重本人原创知识分享,谨记本人博客:南国以南i


提示:以下是本篇文章正文内容,下面案例可供参考

背景

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

第一步:编写代码

1.1 请求层

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

	@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 (multipartFile.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.contains(".")) {
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 解压缩工具类

  1. tar.gz 转换为 tar
  2. 解压 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";
// 要解压到的目录
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();
}
// 将文件写出到解压的目录
IOUtils.copy(fin, new FileOutputStream(curfile));
}

总结

我是南国以南i记录点滴每天成长一点点,学习是永无止境的!转载请附原文链接!!!

参考链接参考链接

有手就会的 Java 处理压缩文件的更多相关文章

  1. java ZIP压缩文件

    问题描述:     使用java ZIP压缩文件和目录 问题解决:     (1)单个文件压缩 注:     以上是实现单个文件写入压缩包的代码,注意其中主要是在ZipOutStream流对象中创建Z ...

  2. java ZipOutputStream压缩文件,ZipInputStream解压缩

    java中实现zip的压缩与解压缩.java自带的 能实现的功能比较有限. 本程序功能:实现简单的压缩和解压缩,压缩文件夹下的所有文件(文件过滤的话需要对File进一步细节处理). 对中文的支持需要使 ...

  3. java生成压缩文件

    在工作过程中,需要将一个文件夹生成压缩文件,然后提供给用户下载.所以自己写了一个压缩文件的工具类.该工具类支持单个文件和文件夹压缩.放代码: import java.io.BufferedOutput ...

  4. java打包压缩文件

    package com.it.simple.util; import java.io.BufferedOutputStream;import java.io.ByteArrayOutputStream ...

  5. Java实现压缩文件与解压缩文件

    由于工作需要,需要将zip的压缩文件进行解压,经过调查发现,存在两个开源的工具包,一个是Apache的ant工具包,另一个就是Java api自带的工具包:但是Java自带的工具包存在问题:如果压缩或 ...

  6. java zip 压缩文件

    zip压缩:ZipOutputStream.ZipFile.ZipInputStream 三个类的作用 一段 java  zip  压缩的代码: File dir = new File("C ...

  7. java对压缩文件进行加密,winrar和好压 直接输入解密密码来使用

    <!-- https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j --> <dependency> <gro ...

  8. Java生成压缩文件(zip、rar 格式)

    jar坐标: <dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</ar ...

  9. Java读取压缩文件信息

    不解压压缩文件,获取其中包含的文件,通过文件名检查是否包含非法文件.(后续再根据文件头或内容吧) zip: import java.util.zip.ZipEntry;import java.util ...

  10. java zip压缩文件和文件夹

    public class FileUtil { /** * 压缩文件-File * @param out zip流 * @param srcFiles 要压缩的文件 * @param path 相对路 ...

随机推荐

  1. 集群监管-USDP(智能大数据平台)

    UCloud Smart Data Platform(简称 USDP),是 UCloud 推出的智能化.轻量级.适用于私有化部署至客户本地的大数据基础服务平台,通过自研的 USDP Manager 管 ...

  2. Github Copilot绑定Jetbrains IDE无效的解决方案

    在Github中进行教育认证后不会自动开通Copilot功能,因此,在进行了Github教育认证之后,在使用之前要进入Github Copilot官网开通Coplilot,如果忽略了这一点,绑定Jet ...

  3. 几种常见Ruby on Rails内置方法介绍

    Ruby on Rails是一个功能强大的WEB开发框架,在这里我们将会学到一些经常用到的Ruby on Rails内置方法,帮助大家熟练掌握其应用技巧. Ruby on Rails自动生成文档技巧大 ...

  4. idea推送代码忽略指定文件,文件夹配置

    idea推送代码忽略指定文件,文件夹配置 今天碰到一个问题,配置了.gitignore文件后没有生效,整了半天,最后发现一种直接配置的方法,可以指定文件夹,或者指定文件类型 打开设置

  5. C语言:找到在文件单词中字符个数最多的单词。

    第一点:这是一个传回指针的指针函数,所以在定义的时候是char*类型的函数,传进的参数是一个文件指针,(敲重点了,一定一定一定要把文件打开了才能传这个文件指针进来!!)因为这是在你的文本文件里面进行查 ...

  6. Java面试题:让依赖注入变得简单,面对@Autowired和@Resource,该如何选择?

    @Autowired和@Resource都是Java Spring框架中的注解,用于实现依赖注入(DI)和控制反转(IoC).它们的区别主要在以下三个方面: 源头不同  @Autowired是Spri ...

  7. Django性能优化:提升加载速度

    title: Django性能优化:提升加载速度 date: 2024/5/20 20:16:28 updated: 2024/5/20 20:16:28 categories: 后端开发 tags: ...

  8. MQTT 实践总结

    QMQX 文档:https://www.emqx.io/docs/zh/latest/ MQTT 入门:https://www.emqx.com/zh/mqtt-guide 通过案例理解 MQTT 主 ...

  9. 【C# wpf】个人网盘练习项目总结

    采用 .net frameowrok 4.5.2 未写持久层代码,不可保存运行时的数据状态.分服务端,客户端,采用tcp通讯,使用了supersocket组件.服务端用winform ,客户端用wpf ...

  10. 到今天了你还不会集合的Stream操作吗?你要out了

    Java8的两个重大改变,一个是Lambda表达式,另一个就是本节要讲的Stream API表达式.Stream 是Java8中处理集合的关键抽象概念,它可以对集合进行非常复杂的查找.过滤.筛选等操作 ...