一、Zip4j介紹
zip4j官網:http://www.lingala.net/zip4j/可以在"download"頁面下載官方示例進行學習。
特征:
從Zip文件創建,添加,提取,更新,刪除文件;
讀/寫受密碼保護的Zip文件和流;
支持AES 128/256加密,支持標準郵編加密;
支持Zip64格式
支持存儲(無壓縮)和Deflate壓縮方法
從Split Zip文件創建或提取文件(例如:z01,z02,... zip)
支持zip 中的Unicode文件名和注釋* Progress Monitor- 集成到應用程序和面向用戶的應用程序
進度監視器
二、需要的引入的jar包
<dependency>
? ? <groupId>net.lingala.zip4j</groupId>
? ? <artifactId>zip4j</artifactId>
? ? <version>2.7.0</version>
</dependency>
三、壓縮整個文件夾
import java.io.File;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel;
import net.lingala.zip4j.model.enums.CompressionMethod;
public class ZipFiles {
private? void zipFile() throws ZipException {
? ? ? ? // 生成的壓縮文件
? ? ? ? ZipFile zipFile = new ZipFile("D:\\test.zip");
? ? ? ? ZipParameters parameters = new ZipParameters();
? ? ? ? // 壓縮方式
? ? ? ? parameters.setCompressionMethod(CompressionMethod.STORE);
? ? ? ? // 壓縮級別
? ? ? ? parameters.setCompressionLevel(CompressionLevel.FAST);
? ? ? ? // 要打包的文件夾
? ? ? ? File currentFile = new File("D:\\test");
? ? ? ? File[] list = currentFile.listFiles();
? ? ? ? // 遍歷test文件夾下所有的文件、文件夾
? ? ? ? for (File f : list) {
? ? ? ? ? ? if (f.isDirectory()) {
? ? ? ? ? ? zipFile.addFile(f.getPath(), parameters);
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? zipFile.addFile(f, parameters);
? ? ? ? ? ? }
? ? ? ? }
? ? }
public static void main(String[] args) {
// TODO Auto-generated method stub
ZipFiles zf = new ZipFiles();
try {
zf.zipFile();
} catch (ZipException e) {
// TODO Auto-generated catch block
e.printStackTrace();
????????}
????}
}
四、
解壓ZIP格式的文件
public static void unzip(String srcFile,String??destDirPath) {
?????????long startTime=System.nanoTime();???//獲取開始時間
?????????try {
?????????????/** 判斷文件是否存在 */
?????????????File file = new File(srcFile);
?????????????if (file.exists()) {
?????????????????/** 判斷文件是否是zip格式的壓縮文件??*/
?????????????????// 獲取文件的后綴
?????????????????String fileSuffix =??file.getName().substring(file.getName().lastIndexOf("."));
?????????????????if (".zip".equals(fileSuffix)) {
??????????????????????net.lingala.zip4j.core.ZipFile zipFile = new??net.lingala.zip4j.core.ZipFile(srcFile);
??????????????????????// 設置編碼格式中文設置為GBK格式
??????????????????????zipFile.setFileNameCharset("GBK");
??????????????????????// 解壓壓縮包
??????????????????????zipFile.extractAll(destDirPath);
?????????????????}
?????????????}
?????????} catch (Exception e) {
?????????????e.printStackTrace();
?????????}
?????????long endTime=System.nanoTime(); //獲取結束時間??
?????????System.out.println("程序運行時間:??"+(endTime-startTime)+"ns");
?????????System.out.println("程序運行時間:??"+(endTime-startTime)/1000000+"ms");
?????????System.out.println("程序運行時間:??"+(endTime-startTime)/1000000000+"s");
????}