一、概述

在本篇文章中,给大家介绍一下如何将文件进行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.txttest2.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;
}
}

欢迎关注我的博客,里面有很多精品合集

  • 本文转载注明出处(必须带连接,不能只转文字):字母哥博客

觉得对您有帮助的话,帮我点赞、分享!您的支持是我不竭的创作动力! 。另外,笔者最近一段时间输出了如下的精品内容,期待您的关注。

使用java API进行zip递归压缩文件夹以及解压的更多相关文章

  1. Java使用线程池递归压缩文件夹下面的所有子文件

    本文将介绍Java中利用线程池递归的方式压缩文件夹下面的所有子文件,具体方法如下: Gzip单个文件压缩 对于单个文件使用GZip压缩. package date0805.demo1; import ...

  2. linux zip,tar压缩文件夹 忽略 .git 文件夾

    linux zip 忽略 .git 文件夾 # zip 命令 zip -r bitvolution.zip bitvolution -x *.git* # tar命令压缩文件夹忽略 .git文件夹 t ...

  3. Java解压上传zip或rar文件,并解压遍历文件中的html的路径

    1.本文只提供了一个功能的代码 public String addFreeMarker() throws Exception { HttpSession session = request.getSe ...

  4. zend framework将zip格式的压缩文件导入并解压到指定文件

    html代码 <pre class="php" name="code"><fieldset> <legend>批量导入学生照 ...

  5. Mint linux 自定义上下文菜单实现ZIP压缩文件无乱码解压

    1. 前提条件 我的Mint Linux 是Thunar文件管理器(默认的). 2. 配置自定义动作 打开Thunar文件管理器,点击菜单“编辑”=>“配置自定义动作”.点击“+”添加一个新的. ...

  6. 简单测试Demo:如何用Java压缩文件夹和文件

    一.直接贴出测试代码 package com.jason.zip; import java.io.File; import java.io.FileInputStream; import java.i ...

  7. C#压缩文件夹至zip,不包含所选文件夹【转+修改】

    转自园友:jimcsharp的博文C#实现Zip压缩解压实例[转] 在此基础上,对其中的压缩文件夹方法略作修正,并增加是否对父文件夹进行压缩的方法.(因为笔者有只压缩文件夹下的所有文件,却不想将选中的 ...

  8. java笔试题: ——将e:/source文件夹下的文件打个zip包后拷贝到f:/文件夹下面

    将e:/source文件夹下的文件打个zip包后拷贝到f:/文件夹下面 import java.io.*; import java.util.zip.ZipEntry; import java.uti ...

  9. Java中往zip压缩包追加文件

    有个需求,从某个接口下载的一个zip压缩包,往里面添加一个说明文件.搜索了一下,没有找到往zip直接添加文件的方法,最终解决方法是先解压.再压缩. 具体过程如下: 1.一个zip文件的压缩和解压工具类 ...

随机推荐

  1. java面试题jvm字节码的加载与卸载

    虚拟机把描述类的数据从class文件加载到内存,并对数据进行校验,转换分析和初始化,最终形成可以被虚拟节直接使用的JAVA类型,这就是虚拟机的类加载机制. 类从被加载到虚拟机内存到卸载出内存的生命周期 ...

  2. Python Ethical Hacking - WEB PENETRATION TESTING(1)

    WHAT IS A WEBSITE Computer with OS and some servers. Apache, MySQL ...etc. Cotains web application. ...

  3. 数据聚合与分组操作知识图谱-《利用Python进行数据分析》

    所有内容整理自<利用Python进行数据分析>,使用MindMaster Pro 7.3制作,emmx格式,源文件已经上传Github,需要的同学转左上角自行下载或者右击保存图片. 其他章 ...

  4. sql 大小写查询 字符串替换 小写xx 改为大写XX

    --sql 大小写查询 select * from 表 where 字段 collate Chinese_PRC_CS_AS='xx' --替换 小写xx 改为大写XX update 表  set  ...

  5. springboot(九)文件上传

    在企业级项目开发过程中,上传文件是最常用到的功能.SpringBoot集成了SpringMVC,当然上传文件的方式跟SpringMVC没有什么出入.下面我们来创建一个SpringBoot项目完成单个. ...

  6. 动态页面技术(EL/JSTL)

    EL技术 EL 表达式概述 EL(Express Lanuage)表达式可以嵌入在jsp页面内部,减少jsp脚本的编写,EL出现的目的是要替代jsp页面中脚本(java代码)的编写. EL从域中取出数 ...

  7. Python获取当前时间_获取格式化时间_格式化日期

    Python获取当前时间_获取格式化时间: Python获取当前时间: 使用 time.time( ) 获取到距离1970年1月1日的秒数(浮点数),然后传递给 localtime 获取当前时间 #使 ...

  8. java反序列化——apache-shiro复现分析

    本文首发于“合天智汇”公众号 作者:Fortheone 看了好久的文章才开始分析调试java的cc链,这个链算是java反序列化漏洞里的基础了.分析调试的shiro也是直接使用了cc链.首先先了解一些 ...

  9. PHP setlocale() 函数

    实例 设置地区为 US English,然后再设置回系统默认: <?php高佣联盟 www.cgewang.comecho setlocale(LC_ALL,"US");ec ...

  10. Echarts饼图绘制

    实现效果: html代码: <div id="chartBody1" style="width:120%;height:28vh;"> <di ...