zip4j实现文件压缩与解压缩 & common-compress压缩与解压缩

时间:2022-05-06 12:30:18

  有时候需要批量下载文件,所以需要在后台将多个文件压缩之后进行下载。

  zip4j可以进行目录压缩与文件压缩,同时可以加密压缩。

  common-compress只压缩文件,没有找到压缩目录的API。

1.zip4j的使用  

pom地址:

        <dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>1.3.2</version>
</dependency>

工具类代码:

package cn.qs.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List; import org.springframework.util.StringUtils; import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants; /**
* 压缩与解压缩文件工具类
*
* @author Administrator
*
*/
public class ZipUtils {
/**
* 根据给定密码压缩文件(s)到指定目录
*
* @param destFileName
* 压缩文件存放绝对路径 e.g.:D:/upload/zip/demo.zip
* @param passwd
* 密码(可为空)
* @param files
* 单个文件或文件数组
* @return 最终的压缩文件存放的绝对路径,如果为null则说明压缩失败.
*/
public static String compress(String destFileName, String passwd, File... files) {
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 压缩方式
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 压缩级别
if (!StringUtils.isEmpty(passwd)) {
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); // 加密方式
parameters.setPassword(passwd.toCharArray());
}
try {
ZipFile zipFile = new ZipFile(destFileName);
for (File file : files) {
zipFile.addFile(file, parameters);
}
return destFileName;
} catch (ZipException e) {
e.printStackTrace();
} return null;
} /**
* 根据给定密码压缩文件(s)到指定位置
*
* @param destFileName
* 压缩文件存放绝对路径 e.g.:D:/upload/zip/demo.zip
* @param passwd
* 密码(可为空)
* @param filePaths
* 单个文件路径或文件路径数组
* @return 最终的压缩文件存放的绝对路径,如果为null则说明压缩失败.
*/
public static String compress(String destFileName, String passwd, String... filePaths) {
int size = filePaths.length;
File[] files = new File[size];
for (int i = 0; i < size; i++) {
files[i] = new File(filePaths[i]);
}
return compress(destFileName, passwd, files);
} /**
* 根据给定密码压缩文件(s)到指定位置
*
* @param destFileName
* 压缩文件存放绝对路径 e.g.:D:/upload/zip/demo.zip
* @param passwd
* 密码(可为空)
* @param folder
* 文件夹路径
* @return 最终的压缩文件存放的绝对路径,如果为null则说明压缩失败.
*/
public static String compressFolder(String destFileName, String passwd, String folder) {
File folderParam = new File(folder);
if (folderParam.isDirectory()) {
File[] files = folderParam.listFiles();
return compress(destFileName, passwd, files);
}
return null;
} /**
* 根据所给密码解压zip压缩包到指定目录
* <p>
* 如果指定目录不存在,可以自动创建,不合法的路径将导致异常被抛出
*
* @param zipFile
* zip压缩包绝对路径
* @param dest
* 指定解压文件夹位置
* @param passwd
* 密码(可为空)
* @return 解压后的文件数组
* @throws ZipException
*/
@SuppressWarnings("unchecked")
public static File[] deCompress(File zipFile, String dest, String passwd) throws ZipException {
// 1.判断指定目录是否存在
File destDir = new File(dest);
if (destDir.isDirectory() && !destDir.exists()) {
destDir.mkdir();
}
// 2.初始化zip工具
ZipFile zFile = new ZipFile(zipFile);
zFile.setFileNameCharset("UTF-8");
if (!zFile.isValidZipFile()) {
throw new ZipException("压缩文件不合法,可能被损坏.");
}
// 3.判断是否已加密
if (zFile.isEncrypted()) {
zFile.setPassword(passwd.toCharArray());
}
// 4.解压所有文件
zFile.extractAll(dest);
List<FileHeader> headerList = zFile.getFileHeaders();
List<File> extractedFileList = new ArrayList<File>();
for (FileHeader fileHeader : headerList) {
if (!fileHeader.isDirectory()) {
extractedFileList.add(new File(destDir, fileHeader.getFileName()));
}
}
File[] extractedFiles = new File[extractedFileList.size()];
extractedFileList.toArray(extractedFiles);
return extractedFiles;
} /**
* 解压无密码的zip压缩包到指定目录
*
* @param zipFile
* zip压缩包
* @param dest
* 指定解压文件夹位置
* @return 解压后的文件数组
* @throws ZipException
*/
public static File[] deCompress(File zipFile, String dest) {
try {
return deCompress(zipFile, dest, null);
} catch (ZipException e) {
e.printStackTrace();
}
return null;
} /**
* 根据所给密码解压zip压缩包到指定目录
*
* @param zipFilePath
* zip压缩包绝对路径
* @param dest
* 指定解压文件夹位置
* @param passwd
* 压缩包密码
* @return 解压后的所有文件数组
*/
public static File[] deCompress(String zipFilePath, String dest, String passwd) {
try {
return deCompress(new File(zipFilePath), dest, passwd);
} catch (ZipException e) {
e.printStackTrace();
}
return null;
} /**
* 无密码解压压缩包到指定目录
*
* @param zipFilePath
* zip压缩包绝对路径
* @param dest
* 指定解压文件夹位置
* @return 解压后的所有文件数组
*/
public static File[] deCompress(String zipFilePath, String dest) {
try {
return deCompress(new File(zipFilePath), dest, null);
} catch (ZipException e) {
e.printStackTrace();
}
return null;
} public static void main(String[] args) {
// 压缩
// compressFolder("G:/sign.zip", "123456", "G:/sign");
// 解压
deCompress("G:/sign.zip", "G:/unzip", "1234567");
}
}

2.common-compress用法

  只能压缩与解压缩文件,支持多种压缩格式,比如:tar、zip、jar等格式,用法大致相同,参考官网即可。

pom地址:

        <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.18</version>
</dependency>
package cn.qs.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutionException; import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.io.IOUtils; public class ZipUtils { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
doUnzipTarfile();
} /**
* 解压缩tar文件
*
* @throws FileNotFoundException
* @throws IOException
*/
private static void doUnzipTarfile() throws FileNotFoundException, IOException {
TarArchiveInputStream inputStream = new TarArchiveInputStream(new FileInputStream("G:/unzip/ttt.tar"));
ArchiveEntry archiveEntry = null;
while ((archiveEntry = inputStream.getNextEntry()) != null) {
// h文件名称
String name = archiveEntry.getName();
// 构造解压出来的文件存放路径
String entryFilePath = "G:/unzip/" + name;
// 读取内容
byte[] content = new byte[(int) archiveEntry.getSize()];
inputStream.read(content);
// 内容拷贝
IOUtils.copy(inputStream, new FileOutputStream(entryFilePath));
} IOUtils.closeQuietly(inputStream);
} /**
* 解压缩zip文件
*
* @throws FileNotFoundException
* @throws IOException
*/
private static void doUnzipZipfile() throws FileNotFoundException, IOException {
ZipArchiveInputStream inputStream = new ZipArchiveInputStream(new FileInputStream("G:/unzip/ttt.zip"));
ArchiveEntry archiveEntry = null;
while ((archiveEntry = inputStream.getNextEntry()) != null) {
// h文件名称
String name = archiveEntry.getName();
// 构造解压出来的文件存放路径
String entryFilePath = "G:/unzip/" + name;
// 读取内容
byte[] content = new byte[(int) archiveEntry.getSize()];
inputStream.read(content);
// 内容拷贝
IOUtils.copy(inputStream, new FileOutputStream(entryFilePath));
} IOUtils.closeQuietly(inputStream);
} /**
* 压缩zip
*
* @throws IOException
* @throws FileNotFoundException
*/
private static void doCompressZip() throws IOException, FileNotFoundException {
ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(new File("G:/unzip/ttt.zip"));
zipOutput.setEncoding("GBK");
zipOutput.setUseZip64(Zip64Mode.AsNeeded);
zipOutput.setMethod(ZipArchiveOutputStream.STORED); // 压一个文件
ZipArchiveEntry entry = new ZipArchiveEntry("ttt.pdf");
zipOutput.putArchiveEntry(entry);
FileInputStream fileInputStream = new FileInputStream(new File("G:/unzip/blank.pdf"));
IOUtils.copyLarge(fileInputStream, zipOutput);
IOUtils.closeQuietly(fileInputStream);
zipOutput.closeArchiveEntry(); // 压第二个文件
ZipArchiveEntry entry1 = new ZipArchiveEntry("killTomcat.bat");
zipOutput.putArchiveEntry(entry1);
FileInputStream fileInputStream1 = new FileInputStream(new File("G:/unzip/springboot.log"));
IOUtils.copyLarge(fileInputStream1, zipOutput);
IOUtils.closeQuietly(fileInputStream1);
zipOutput.closeArchiveEntry(); IOUtils.closeQuietly(zipOutput);
} /**
* 压缩tar
*
* @throws IOException
* @throws FileNotFoundException
*/
private static void doCompressTar() throws IOException, FileNotFoundException {
TarArchiveOutputStream tarOut = new TarArchiveOutputStream(new FileOutputStream("G:/unzip/ttt.tar")); // 压一个文件
TarArchiveEntry entry = new TarArchiveEntry("ttt.pdf");
File file = new File("G:/unzip/ttt.pdf");
entry.setSize(file.length());
tarOut.putArchiveEntry(entry);
FileInputStream fileInputStream = new FileInputStream(file);
IOUtils.copyLarge(fileInputStream, tarOut);
IOUtils.closeQuietly(fileInputStream);
tarOut.closeArchiveEntry(); // 压第二个文件
TarArchiveEntry entry1 = new TarArchiveEntry("killTomcat.bat");
File file2 = new File("G:/unzip/killTomcat.bat");
entry1.setSize(file2.length());
tarOut.putArchiveEntry(entry1);
FileInputStream fileInputStream1 = new FileInputStream(file2);
IOUtils.copyLarge(fileInputStream1, tarOut);
IOUtils.closeQuietly(fileInputStream1);
tarOut.closeArchiveEntry(); IOUtils.closeQuietly(tarOut);
}
}

zip4j实现文件压缩与解压缩 & common-compress压缩与解压缩的更多相关文章

  1. 压缩和解压文件:tar gzip bzip2 compress&lpar;转&rpar;

    tar[必要参数][选择参数][文件] 压缩:tar -czvf filename.tar.gz targetfile解压:tar -zxvf filename.tar.gz参数说明: -c 建立新的 ...

  2. java zip4j 内存文件和磁盘文件 压缩和加密

    经常服务器需要对文件进行压缩,网络上流传较多的是从磁盘文件中来压缩成zip文件.但是常常服务器的文件存放在内存中,以byte[]形式存储在内存中.这个时候就不能使用网络上流传的常用方法了,这里就需要对 ...

  3. 【Linux】【二】linux 压缩文件(txt)、查看压缩文件内容、解压缩文件、

    通过Xshell 压缩文件.解压缩文件 gzip tools.txt 压缩[tools.txt]文件 zcat tools.txt.gz   查看压缩文件[tools.txt.gz]内容 gunzip ...

  4. Zip文件压缩(加密&vert;&vert;非加密&vert;&vert;压缩指定目录&vert;&vert;压缩目录下的单个文件&vert;&vert;根据路径压缩&vert;&vert;根据流压缩)

    1.写入Excel,并加密压缩.不保存文件 String dcxh = String.format("%03d", keyValue); String folderFileName ...

  5. Linux 压缩备份篇(一 压缩与解压缩)

    .Z                compress程序压缩的档案 .bz2                bzip2程序压缩的档案 .gz                gzip程序压缩的档案 .t ...

  6. Android开发 ---从互联网上下载文件,回调函数,图片压缩、倒转

     Android开发 ---从互联网上下载文件,回调函数,图片压缩.倒转 效果图: 描述: 当点击“下载网络图像”按钮时,系统会将图二中的照片在互联网上找到,并显示在图像框中 注意:这个例子并没有将图 ...

  7. shutil模块---文件,文件夹复制、删除、压缩等处理

    shutil模块:高级的文件,文件夹,压缩包处理 拷贝内容 # shutil.copyfileobj(open('example.ini','r'),open('example.new','w')) ...

  8. IIS7&period;5打开GZip压缩,同时启用GZip压缩JS&sol;CSS文件的设置方法&lbrack;bubuko&period;com&rsqb;

    IIS7.5或者IIS7.0开启GZip压缩方法:打开IIS,在右侧点击某个网站,在功能视图中的“IIS”区域,双击进入“压缩”,如图下图: 分别勾选“启用动态内容压缩”和“启用静态内容压缩”.这样最 ...

  9. mac 命令行上传文件,mac tar&period;gz命令压缩

    在mac上可以直接打开命令行给服务器上传文件,注意是本地的命令行,不是服务器的命令行,我就走了绕路 命令可以看这里https://www.cnblogs.com/hitwtx/archive/2011 ...

随机推荐

  1. 消息服务MNS和消息队列ONS产品对比

    消息服务MNS和消息队列ONS产品对比 MNS已经进过严格测试,已达到商业化的稳定性要求,其主要特点和适用场景 1.数据高可靠(10个9),对于数据可靠性敏感(要求消息数据不丢)的应用场景建议选择. ...

  2. C&num; 方法调用的切换器 Update 2015&period;02&period;02

    在编写应用程序时,我们经常要处理这样的一组对象,它们的类型都派生自同一个基类,但又需要为每个不同的子类型应用不同的处理方法. 通常的做法,最简单的就是用很多 if-else 去判断各自的类型,如下面的 ...

  3. SQL Server -&gt&semi;&gt&semi; 深入探讨SQL Server 2016新特性之 --- Temporal Table(历史表)

    原文:SQL Server ->> 深入探讨SQL Server 2016新特性之 --- Temporal Table(历史表) 作为SQL Server 2016(CTP3.x)的另一 ...

  4. yii 分页样式

    需求及效果图如下 没什么说的,就是修改分页,修改了CLinks分页的样式 上代码 <?php class GsearchPager extends CBasePager { const CSS_ ...

  5. 安装arcgis server 10&period;2遇到的问题总结

    1.创建管理站点失败 错误提示:Failed to create the site. The machine does not have a valid license. Please authori ...

  6. Jenkins远程部署SpringBoot应用

    一般Web工程通过Jenkins远程部署到Tomcat,可以采用Maven的tomcat-maven-plugin插件进行部署.最近接触到Spring Boot工程的部署,由于Spring Boot应 ...

  7. color 圆盘染色

    Color 圆盘染色 题目大意:给你一个圆盘,等分成n个扇形,有m种颜色,每两个相邻的扇形不能相交,求染色方案数. 注释:m,n<=$10^6$. 想法:这题是小圆盘染色的加强版(小圆盘染色?) ...

  8. jsoncpp linux平台编译和arm移植

    下载 http://sourceforge.net/projects/jsoncpp/ 或者 http://download.csdn.net/detail/chinaeran/8631141 Lin ...

  9. MSMQ &period;NET下的应用

    Message Message是MSMQ的数据存储单元,我们的用户数据一般也被填充在Message的body当中,因此很重要,让我们来看一看其在.net中的体现,如图: 在图上我们可以看见,Messa ...

  10. qt tcp 通信实例

    #include "mainwindow.h" #include "ui_mainwindow.h" #include <QHostAddress> ...