@


前言

请各大网友尊重本人原创知识分享,谨记本人博客:南国以南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. ITIL一定要去认证吗?哪个版本合适

    关于ITIL的演进 ITIL是在演进发展中的,v1并不成功,v2 v3讲究流程与控制,其实都是偏向务虚,理论东西较多,能落地的少或许OGC的专家们自己也发现 光靠口头忽悠并不能说服最终用户接受ITIL ...

  2. 06. C语言指针

    [指针] C语言使用数据名调用数据,数据名相当于C语言的直接寻址,直接寻址只能调用固定数据,而指针是间接寻址,指针存储了另一个数据的地址,使用指针调用数据时首先取指针存储的内存地址,之后使用此地址调用 ...

  3. leaflet利用hotline实现河流差值渲染热力图

    实现效果(这里做了1条主河道和5个支流): 核心代码使用了Leaflet.hotline插件,github下载地址链接 详情见我之前整理的一篇文章介绍河流热力图 核心代码逻辑: // 处理河流数据以及 ...

  4. python小功能

    django实现将linux目录和文件名列出来 def index(request): obj=models.USER.objects.all() fileroot = 'd:\machangwei' ...

  5. CMake 进行多项目中dll的编译和链接

    前言(maybe废话) 最近正在学习cherno的游戏引擎教程,他使用的是vs进行构建的,后面换了premake.而我用的是vscode+cmake,所以在构建整个项目的时候踩了不少的坑,也找了很多资 ...

  6. OpenCV笔记(10) 相机模型与标定

    万圣节快乐! 1. 相机模型 针孔相机模型:过空间某特定点的光线才能通过针孔(针孔光圈),这些光束被投影 到图像平面形成图像. 将图像平面在针孔前方,重新把针孔相机模型整理成另一种等价形式, 实际上, ...

  7. C# || 批量翻译工具 || 百度翻译api || 读取.cs文件内容 || 正则表达式筛选文件

    背景: 我们项目一开始的所有提示都是中文,后来要做国际化.发现项目中的带双引号的中文居然有 2.3 w 多条!!!简直让人欲哭无泪... 如果使用人工改的话,首先不说正确率了.光是效率都是难难难.所以 ...

  8. 内存优化:Boxing

    dotMemory 如今,许多开发人员都熟悉性能分析的工作流程:在分析器下运行应用程序,测量方法的执行时间,识别占用时间较多的方法,并致力于优化它们.然而,这种情况并没有涵盖到一个重要的性能指标:应用 ...

  9. minos 2.1 中断虚拟化——ARMv8 异常处理

    首发公号:Rand_cs 越往后,交叉的越多,大多都绕不开 ARMv8 的异常处理,所以必须得先了解了解 ARMv8 的异常处理流程 先说一下术语,从手册中的用词来看,在 x86 平台,一般将异常和中 ...

  10. kettle从入门到精通 第三十七课 kettle 全量同步(数据量小)

    1.下图是一些常见的数据同步业务场景: 实时数据:对实时性要求很高,延迟在毫秒范围内.常见的有kafka/rabbitmq等消息中间件,mysql binlog日志,oracle归档日志等. 离线数据 ...