使用java API进行zip递归压缩文件夹以及解压
一、概述
在本篇文章中,给大家介绍一下如何将文件进行zip压缩以及如何对zip包解压。所有这些都是使用Java提供的核心库java.util.zip来实现的。
二、压缩文件
首先我们来学习一个简单的例子-压缩单个文件。将一个名为test1.txt的文件压缩到一个名为Compressed.zip的zip文件中。
public class ZipFile {
public static void main(String[] args) throws IOException {
//输出压缩包
FileOutputStream fos = new FileOutputStream("src/main/resources/compressed.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos);
//被压缩文件
File fileToZip = new File("src/main/resources/test1.txt");
FileInputStream fis = new FileInputStream(fileToZip);
//向压缩包中添加文件
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
zipOut.close();
fis.close();
fos.close();
}
}
三、压缩多个文件
接下来,我们看看如何将多个文件压缩为一个zip文件。我们将把test1.txt和test2.txt压缩成multiCompressed.zip:
public class ZipMultipleFiles {
public static void main(String[] args) throws IOException {
List<String> srcFiles = Arrays.asList("src/main/resources/test1.txt", "src/main/resources/test2.txt");
FileOutputStream fos = new FileOutputStream("src/main/resources/multiCompressed.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos);
//向压缩包中添加多个文件
for (String srcFile : srcFiles) {
File fileToZip = new File(srcFile);
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
zipOut.close();
fos.close();
}
}
四、压缩目录
下面的例子,我们将zipTest目录及该目录下的递归子目录文件,全都压缩到dirCompressed.zip中:
public class ZipDirectory {
public static void main(String[] args) throws IOException, FileNotFoundException {
//被压缩的文件夹
String sourceFile = "src/main/resources/zipTest";
//压缩结果输出,即压缩包
FileOutputStream fos = new FileOutputStream("src/main/resources/dirCompressed.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos);
File fileToZip = new File(sourceFile);
//递归压缩文件夹
zipFile(fileToZip, fileToZip.getName(), zipOut);
//关闭输出流
zipOut.close();
fos.close();
}
/**
* 将fileToZip文件夹及其子目录文件递归压缩到zip文件中
* @param fileToZip 递归当前处理对象,可能是文件夹,也可能是文件
* @param fileName fileToZip文件或文件夹名称
* @param zipOut 压缩文件输出流
* @throws IOException
*/
private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
//不压缩隐藏文件夹
if (fileToZip.isHidden()) {
return;
}
//判断压缩对象如果是一个文件夹
if (fileToZip.isDirectory()) {
if (fileName.endsWith("/")) {
//如果文件夹是以“/”结尾,将文件夹作为压缩箱放入zipOut压缩输出流
zipOut.putNextEntry(new ZipEntry(fileName));
zipOut.closeEntry();
} else {
//如果文件夹不是以“/”结尾,将文件夹结尾加上“/”之后作为压缩箱放入zipOut压缩输出流
zipOut.putNextEntry(new ZipEntry(fileName + "/"));
zipOut.closeEntry();
}
//遍历文件夹子目录,进行递归的zipFile
File[] children = fileToZip.listFiles();
for (File childFile : children) {
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
}
//如果当前递归对象是文件夹,加入ZipEntry之后就返回
return;
}
//如果当前的fileToZip不是一个文件夹,是一个文件,将其以字节码形式压缩到压缩包里面
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileName);
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
}
- 要压缩子目录及其子目录文件,所以需要递归遍历
- 每次遍历找到的是目录时,我们都将其名称附加“/”,并将其以ZipEntry保存到压缩包中,从而保持压缩的目录结构。
- 每次遍历找到的是文件时,将其以字节码形式压缩到压缩包里面
五、解压缩zip压缩包
下面为大家举例讲解解压缩zip压缩包。在此示例中,我们将compressed.zip解压缩到名为unzipTest的新文件夹中。
public class UnzipFile {
public static void main(String[] args) throws IOException {
//被解压的压缩文件
String fileZip = "src/main/resources/unzipTest/compressed.zip";
//解压的目标目录
File destDir = new File("src/main/resources/unzipTest");
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
//获取压缩包中的entry,并将其解压
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
File newFile = newFile(destDir, zipEntry);
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
//解压完成一个entry,再解压下一个
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
//在解压目标文件夹,新建一个文件
public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
File destFile = new File(destinationDir, zipEntry.getName());
String destDirPath = destinationDir.getCanonicalPath();
String destFilePath = destFile.getCanonicalPath();
if (!destFilePath.startsWith(destDirPath + File.separator)) {
throw new IOException("该解压项在目标文件夹之外: " + zipEntry.getName());
}
return destFile;
}
}
欢迎关注我的博客,里面有很多精品合集
- 本文转载注明出处(必须带连接,不能只转文字):字母哥博客。
觉得对您有帮助的话,帮我点赞、分享!您的支持是我不竭的创作动力! 。另外,笔者最近一段时间输出了如下的精品内容,期待您的关注。
- 《手摸手教你学Spring Boot2.0》
- 《Spring Security-JWT-OAuth2一本通》
- 《实战前后端分离RBAC权限管理系统》
- 《实战SpringCloud微服务从青铜到王者》
- 《VUE深入浅出系列》
使用java API进行zip递归压缩文件夹以及解压的更多相关文章
- Java使用线程池递归压缩文件夹下面的所有子文件
本文将介绍Java中利用线程池递归的方式压缩文件夹下面的所有子文件,具体方法如下: Gzip单个文件压缩 对于单个文件使用GZip压缩. package date0805.demo1; import ...
- linux zip,tar压缩文件夹 忽略 .git 文件夾
linux zip 忽略 .git 文件夾 # zip 命令 zip -r bitvolution.zip bitvolution -x *.git* # tar命令压缩文件夹忽略 .git文件夹 t ...
- Java解压上传zip或rar文件,并解压遍历文件中的html的路径
1.本文只提供了一个功能的代码 public String addFreeMarker() throws Exception { HttpSession session = request.getSe ...
- zend framework将zip格式的压缩文件导入并解压到指定文件
html代码 <pre class="php" name="code"><fieldset> <legend>批量导入学生照 ...
- Mint linux 自定义上下文菜单实现ZIP压缩文件无乱码解压
1. 前提条件 我的Mint Linux 是Thunar文件管理器(默认的). 2. 配置自定义动作 打开Thunar文件管理器,点击菜单“编辑”=>“配置自定义动作”.点击“+”添加一个新的. ...
- 简单测试Demo:如何用Java压缩文件夹和文件
一.直接贴出测试代码 package com.jason.zip; import java.io.File; import java.io.FileInputStream; import java.i ...
- C#压缩文件夹至zip,不包含所选文件夹【转+修改】
转自园友:jimcsharp的博文C#实现Zip压缩解压实例[转] 在此基础上,对其中的压缩文件夹方法略作修正,并增加是否对父文件夹进行压缩的方法.(因为笔者有只压缩文件夹下的所有文件,却不想将选中的 ...
- java笔试题: ——将e:/source文件夹下的文件打个zip包后拷贝到f:/文件夹下面
将e:/source文件夹下的文件打个zip包后拷贝到f:/文件夹下面 import java.io.*; import java.util.zip.ZipEntry; import java.uti ...
- Java中往zip压缩包追加文件
有个需求,从某个接口下载的一个zip压缩包,往里面添加一个说明文件.搜索了一下,没有找到往zip直接添加文件的方法,最终解决方法是先解压.再压缩. 具体过程如下: 1.一个zip文件的压缩和解压工具类 ...
随机推荐
- day6:双向循环练习&pass_break_continue&for循环
双向循环练习 1.打印10行10列的小星星(两个循环) # j 外循环用来控制行数 j = 0 while j < 10: # i 打印一行十个星星 i = 0 while i < 10: ...
- 你真的清楚DateTime in C#吗?
DateTime,就是一个世界的大融合. 日期和时间,在我们开发中非常重要.DateTime在C#中,专门用来表达和处理日期和时间. 本文算是多年使用DateTime的一个总结,包括DateTim ...
- Go的100天之旅-08字符串
目录 简介 UTF-8字符 字符串的常用操作 简介 字符串在各种编程语言中都是很基础的一种类型,在Go中字符串简单理解就是一个数组,数组里面的元素是byte类型.因此基本上拥有类似数组的全部特性.例如 ...
- echarts 踩坑 : 为什么触摸柱状图的时后柱子不见了?原来是color的锅!
今天发现一个奇怪的问题. 当我的鼠标触摸柱状图的时候,柱状图就消失了. 后来发现是颜色的设置有问题. color: ['rgba(68,238,224)', 'rgba(17,215,255)', ' ...
- DJANGO-天天生鲜项目从0到1-005-FastDFS与Nginx打造自定义文件存储系统
本项目基于B站UP主‘神奇的老黄’的教学视频‘天天生鲜Django项目’,视频讲的非常好,推荐新手观看学习 https://www.bilibili.com/video/BV1vt41147K8?p= ...
- $0.\dot{9}=1,是指以1为极限,而非初等数学的相等“=”$
$注:文中的讨论,没有使用严格的 \epsilon 极限定义,而是简单假设$ 按照中小学的定义,整数,有限小数,无限循环小数是有理数.无限不循环小数是无理数. $\frac{1}{3}=0.\dot{ ...
- PHP设计模式之----简单工厂模式
定义个抽象的类(或接口),让子类去继承(实现)它 abstract class Operation { abstract public function getValue($num1, $num2); ...
- Day15_用户注册
学于黑马和传智播客联合做的教学项目 感谢 黑马官网 传智播客官网 微信搜索"艺术行者",关注并回复关键词"乐优商城"获取视频和教程资料! b站在线视频 0.学习 ...
- cmd 安装第三方库问题
pip install 包名 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com 一定要指定 信任豆瓣源,不然就算换了源 ...
- PHP md5_file() 函数
实例 计算文本文件 "test.txt" 的 MD5 散列: <?php高佣联盟 www.cgewang.com$filename = "test.txt" ...