@


前言

请各大网友尊重本人原创知识分享,谨记本人博客:南国以南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. vue路由跳转的三种方式

    目录 1.router-link [实现跳转最简单的方法] 2.this.$router.push({ path:'/user'}) 3.this.$router.replace{path:'/' } ...

  2. postgresql 开启审计日志

    1.审计清单说明 logging_collector     --是否开启日志收集开关,默认off,推荐on log_destination       --日志记录类型,默认是stderr,只记录错 ...

  3. Selenium4自动化测试3--元素定位By.NAME,By.LINK_TEXT 和通过链接部分文本定位,By.PARTIAL_LINK_TEXT,css_selector定位,By.CSS_SELECTOR

    4-通过名称定位,By.NAME name属性为表单中客户端提交数据的标识,一个网页中name值可能不是唯一的.所以要根据实际情况进行判断 import time from selenium impo ...

  4. Django性能之道:缓存应用与优化实战

    title: Django性能之道:缓存应用与优化实战 date: 2024/5/11 18:34:22 updated: 2024/5/11 18:34:22 categories: 后端开发 ta ...

  5. OpenStack Centos7 T版本搭建

    目录 Centos7搭建OpenStack T版本 --上 1. 环境准备(所有节点操作) 1.1 修改主机名 1.2 关闭selinux 以及防火墙 1.3 修改hosts 1.4 配置时间同步 c ...

  6. Django与前端框架协作开发实战:高效构建现代Web应用

    title: Django与前端框架协作开发实战:高效构建现代Web应用 date: 2024/5/22 20:07:47 updated: 2024/5/22 20:07:47 categories ...

  7. 使用interface化解一场因操作系统不同导致的编译问题

    场景描述 起因: 因项目需求,需要编写一个agent, 需支持Linux和Windows操作系统. Agent里面有一个功能需要获取到服务器上所有已经被占用的端口. 实现方式:针对不同的操作系统,实现 ...

  8. 为datagridview添加自定义按钮

    先上图: 我是直接网上搜得代码,不是本人写得.下面说说大体思路,继承DataGridViewButtonCell类实现自定义类比如这个:DataGridViewDetailButtonCell 里面, ...

  9. Pandas学习之路【3】

    新增列的一些操作 1.新增一个列,直接给列赋值 # 取所有行,新增的列为new_col df.loc[:, 'new_col'] = 100 2.使用df.apply方法给新增的列赋值 def get ...

  10. OpenVSCode云端IDE加入Rainbond一体化开发体系

    OpenVSCode 是一款基于Web 界面的在线IDE 代码编辑器,只需要PC端存在浏览器即可使用,更轻量,高效,简洁,其基础功能完全继承了微软出品的 VS Code ,可以通过安装扩展的方式继续加 ...