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

  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. Var的用法解析

    C#关键字是伴随着.NET 3.5以后,伴随着匿名函数.LINQ而来, 由编译器帮我们推断具体的类型.总体来说,当一个变量是局部变量(不包括类级别的变量),并且在声明的时候初始化,是使用var关键字的 ...

  2. openstack第一章:keystone

    第一篇keystone— 身份认证服务 一.Keystone介绍:       keystone 是OpenStack的组件之一,用于为OpenStack家族中的其它组件成员提供统一的认证服务,包括身 ...

  3. Aninteresting game HDU - 5975 (数学+lowbit)

    Let’s play a game.We add numbers 1,2...n in increasing order from 1 and put them into some sets. Whe ...

  4. bzoj4785:[ZJOI2017]树状数组:二维线段树

    分析: "如果你对树状数组比较熟悉,不难发现可怜求的是后缀和" 设数列为\(A\),那么可怜求的就是\(A_{l-1}\)到\(A_{r-1}\)的和(即\(l-1\)的后缀减\( ...

  5. flask 利用flask_wtf扩展 创建web表单

    在Flask中,为了处理web表单,我们一般使用Flask-WTF扩展,它封装了WTForms,并且它有验证表单数据的功能 创建语句格式: startTime = DateTimeField('计划开 ...

  6. 一、Log4Net配置

    Core的配置 一.创建core包含控制和视图的项目以及Log4Net引用 二.创建Log4Net配置文件 右击项目->添加文件   Log4Net.config 2 复制以下代码 以下配置可做 ...

  7. 洛谷P1122最大子树和题解

    题目 一道比较好想的树形\(DP\) 完全可以用树形DP的基本思路,递归,然后取最优的方法. \(Code\) #include <iostream> #include <cstri ...

  8. 老年OIer的Python实践记—— Codeforces Round #555 (Div. 3) solution

    对没错下面的代码全部是python 3(除了E的那个multiset) 题目链接:https://codeforces.com/contest/1157 A. Reachable Numbers 按位 ...

  9. JS生成随机数进行循环匹配数组

    function RndNum(n) { var rnd = ""; for (var i = 0; i < n; i++) rnd += Math.floor(Math.r ...

  10. <TCP/IP原理> (三) 底层网络技术

    传输介质 局域网(LAN) 交换(Switching) 广域网(WAN) 连接设备 第三章 底层网络技术 引言 1)Interne不是一种新的网络 建立在底层网络上的网际网 底层网络——“物理网”,网 ...