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

  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(转)

    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文件压缩(加密||非加密||压缩指定目录||压缩目录下的单个文件||根据路径压缩||根据流压缩)

    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.5打开GZip压缩,同时启用GZip压缩JS/CSS文件的设置方法[bubuko.com]

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

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

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

随机推荐

  1. EntityFramework 6.x和EntityFramework Core关系映射中导航属性必须是public?

    前言 不知我们是否思考过一个问题,在关系映射中对于导航属性的访问修饰符是否一定必须为public呢?如果从未想过这个问题,那么我们接下来来探讨这个问题. EF 6.x和EF Core 何种情况下必须配 ...

  2. postman使用详解

    前言: Postman是一款功能强大的网页调试与发送网页HTTP请求的Chrome插件. 接口请求流程 一.get请求 GET请求:点击Params,输入参数及value,可输入多个,即时显示在URL ...

  3. To B Vs To C

    谈谈 To B 业务的难点https://tangjie.me/blog/259.html

  4. Azure DevOps

    Azure DevOps https://azure.microsoft.com/zh-cn/services/devops/ It looks great!

  5. JS学习笔记Day21

    一.mySQL数据库 (一)数据库的概念 1.概念:可以存储数据的一个仓库 2.结构化数据:以表格的形式展现,结构更清晰,这样的数据称之为结构化数据 (二)数据库管理软件 1.一种对数据库文件进行管理 ...

  6. 关于rocketmq的配置启动

    #集群名称brokerClusterName=rocket-nameserver#broker-a,注意其它两个分别为broker-b和broker-cbrokerName=broker-a#brok ...

  7. 【Mac上的PotPlayer视频播放器】Movist Pro for Mac 2.1.2

    [简介] Movist 是Mac上最好用的视频播放器之一,功能齐全,类似Windows上的PotPlayer,今天和大家分享最新的 2.1.2 中文版本,Movist 支持几乎所有常见的视频格式,包括 ...

  8. python3.x执行post请求时报错“POST data should be bytes or an iterable of bytes...”的解决方法

    使用python3.5.1执行post请求时,一直报错"POST data should be bytes or an iterable of bytes. It cannot be of ...

  9. woe_iv原理和python代码建模

    python信用评分卡(附代码,博主录制) https://study.163.com/course/introduction.htm?courseId=1005214003&utm_camp ...

  10. 基于前后端分离的Nginx+Tomcat动静分离

    1.什么是动静分离 "动"与"静" 在弄清动静分离之前,我们要先明白什么是动,什么是静. 在Web开发中,通常来说,动态资源其实就是指那些后台资源,而静态资源就 ...