JAVA使用Zip工具包压缩文件为zip格式(1)——单文件压缩
一、使用场景概述
将文件压缩为zip格式的需求,避免踩坑,这篇文章教大家如何使用java.util.zip与java-io进行文件的zip格式压缩。
本章仅适用于单个文件压缩,后续会持续更新,多个文件、文件夹压缩,点个关注,不迷路哦!
二、准备工作
- 开发环境
java 1.8
springboot2.0版本
maven - 相关依赖
jdk 1.8提供
三、具体实现
涉及的主要类:ZipOutputStream(压缩文件流处理类)
大家可以根据自己需求将以下代码封装为工具类,这样拿到哪里都可以用:
1. 实现代码
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/** Zip工具类
* @author getao
* @date 2022/7/1 16:31
*/
public class ZipUtils {
/**
* 压缩文件到指定路径
* @param sourcePath 源文件路径
* @param targetZipPath 目标路径
*/
public static void pathTOZipFile(String sourcePath, String targetZipPath) {
File sourceFile = new File(sourcePath);
File targetZipFile = new File(targetZipPath);
// 如果目标路径不存在,就创建父级目录,暂不考虑系统权限问题
if (!targetZipFile.getParentFile().exists()) {
targetZipFile.getParentFile().mkdir();
}
try {
// 创建目标压缩文件保存路径输出流
FileOutputStream outputStream = new FileOutputStream(targetZipFile);
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
// 如果是单个文件
ZipEntry zipEntry = new ZipEntry(sourceFile.getName());
zipOutputStream.putNextEntry(zipEntry);
FileInputStream inputStream = new FileInputStream(sourceFile);
byte[] buffer = new byte[1024];
int len = 0;
while ((len=inputStream.read(buffer)) >=0 ) {
zipOutputStream.write(buffer, 0, len);
}
// 释放资源
zipOutputStream.close();
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/** 可使用以下代码测试,注意更换为自己电脑中的路径
* @author getao
* @date 2022/7/1 16:31
*/
public static void main(String[] args) throws IOException, FileNotFoundException {
// 源文件路径
String sourcePath = "C:\\Users\\getao\\Desktop\\s3afn5yfmjj.jpg";
// 压缩路径
String targetPath = "C:\\Users\\getao\\Desktop\\james.zip";
// 调用压缩方法
pathTOZipFile(sourcePath, targetPath);
System.out.println("文件:" + sourcePath + "压缩成功啦!");
}
}
2. 测试结果
叮~亲测有效,到你的压缩位置看下,文件可以正常解压并浏览,大功告成!!!
文件:C:\Users\getao\Desktop\s3afn5yfmjj.jpg压缩成功啦!
Process finished with exit code 0
如果有其他好的想法,欢迎评论区交流。