zip4j实现文件压缩与解压缩 common-compress压缩与解压缩
有时候需要批量下载文件,所以需要在后台将多个文件压缩之后进行下载。
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);} }
转载于:https://www.cnblogs.com/qlqwjy/p/10770222.html
zip4j实现文件压缩与解压缩 common-compress压缩与解压缩相关推荐
- 压缩和解压文件:tar gzip bzip2 compress(转)
tar[必要参数][选择参数][文件] 压缩:tar -czvf filename.tar.gz targetfile 解压:tar -zxvf filename.tar.gz 参数说明: -c 建 ...
- 使用SQL Storage Compress压缩SQL Server 数据库文件
2013-01-07 17:1711人阅读评论(0)收藏编辑删除 这几天在测试SQL Server数据压缩功能,通过对数据仓库表启用压缩,磁盘空间大大减小,查询性能和备份速度都有提高.但是SQL Se ...
- java实现linux中gzip压缩解压缩算法:byte[]字节数组,文件,字符串,数据流的压缩解压缩
全栈工程师开发手册 (作者:栾鹏) java教程全解 java实现gzip压缩解压缩byte[]字节数组,文件,字符串. 测试代码 public static void main(String[] a ...
- Java使用zip4j进行文件压缩
pom依赖: <!-- https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j --> <dependency>& ...
- linux中用zip压缩文件,详解Linux中zip压缩和unzip解压缩命令及使用详解
下面给大家介绍下Linux中zip压缩和unzip解压缩命令详解 1.把/home目录下面的mydata目录压缩为mydata.zip zip -r mydata.zip mydata #压缩myda ...
- linux 常用压缩命令,Linux常用的压缩及解压缩命令
Linux常用的压缩及解压缩命令如表1所示. 表1 Linux常用的压缩及解压缩命令说明 常用命令 简要中文说明 程序所在目录 gzip 压缩成文件名为.gz的压缩文件(也可用–d选项变成解压) /b ...
- linux 压缩固定大小,tar gz压缩文件为指定大小
tar -c: 建立压缩档案 -x:解压 -t:查看内容 -r:向压缩归档文件末尾追加文件 -u:更新原压缩包中的文件 这五个是独立的命令,压缩解压都要用到其中一个,可以和别的命令连用但只能用其中一个 ...
- [重学Java基础][Java IO流][Exter.1]Apache Commonms Compress压缩工具包
Apache Commons Compress 简介 Apache Commons Copress是 Apache Commons系列工具的一个部分 是一个提供了更丰富的压缩功能和支持更多压缩格式的工 ...
- linux compress压缩命令
文章目录 linux compress命令 参考 linux compress命令 compress命令使用"Lempress-Ziv"编码压缩数据文件.compress是个历史悠 ...
- Linux打包压缩:zcat、compress、gzip、bzip、xz、zip、tar、cpio
文章目录 常见解压/压缩命令 压缩.解压缩工具 一.zcat 显示压缩包中文件的内容 (一).语法 (二).参数 (三).常用命令查看压缩包内容命令: 二.compress/uncompress压缩工 ...
最新文章
- 安装 sklearn 报错 ImportError: cannot import name Type
- 剑指云内存数据库,阿里云在下一盘大棋
- Localhost与数据库连接
- [Ext JS 4] 实战Chart 协调控制(单一的坐标,两个坐标)
- C#程序设计笔记(第九章)
- 小工匠聊架构-超高并发秒杀系统设计 01_总体原则和架构演进
- 复现经典:《统计学习方法》第 8 章 提升方法
- Response_案例2_输出字符数据
- c语言一个循环重新输入密码,想程序高手求助--用C语言来编辑一个输入密码的程序...
- sql企业管理器_Valentina Studio for mac(开源数据库管理器)
- 微信小程序的setData
- 小程序promise封装post请求_Promise封装微信小程序的Request请求
- 状态管理之cookie使用及其限制、session会话
- 安卓学习-界面-ui-Spinner
- 实现Servlet接口来开发Servlet程序
- JavaWeb学习笔记
- esp分区引导修复失败_让你彻底理解和学会UEFI启动模式下修复引导问题的教程-网络教程与技术
-亦是美网络...
- PLM系统的经济收益
- Unix/Linux编程:Internet domain socket
- Angular开发(三)-关于属性绑定与事件绑定