package com.han;
import java.io.*;
import java.util.zip.*;
/**
* 程序實現了ZIP壓縮。***分為2部分 : 壓縮(compression)與解壓(decompression)
* <p>
* 大致功能包括用了多態,遞歸等JAVA核心技術,可以對單個文件和任意級聯文件夾進行壓縮和解壓。 需在代碼中自定義源輸入路徑和目標輸出路徑。
* <p>
* 在本段代碼中,實現的是壓縮部分;解壓部分見本包中Decompression部分。
*
* @author HAN
*
*/
public class MyZipCompressing {
private int k = 1; // 定義遞歸次數變量
public MyZipCompressing() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyZipCompressing book = new MyZipCompressing();
try {
book.zip("C:\\Users\\Gaowen\\Desktop\\ZipTestCompressing.zip",
new File("C:\\Users\\Gaowen\\Documents\\Tencent Files"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void zip(String zipFileName, File inputFile) throws Exception {
System.out.println("壓縮中...");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
BufferedOutputStream bo = new BufferedOutputStream(out);
zip(out, inputFile, inputFile.getName(), bo);
bo.close();
out.close(); // 輸出流關閉
System.out.println("壓縮完成");
}
private void zip(ZipOutputStream out, File f, String base,
BufferedOutputStream bo) throws Exception { // 方法重載
if (f.isDirectory()) {
File[] fl = f.listFiles();
if (fl.length == 0) {
out.putNextEntry(new ZipEntry(base + "/")); // 創建zip壓縮進入點base
System.out.println(base + "/");
}
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + "/" + fl[i].getName(), bo); // 遞歸遍歷子文件夾
}
System.out.println("第" + k + "次遞歸");
k++;
} else {
out.putNextEntry(new ZipEntry(base)); // 創建zip壓縮進入點base
System.out.println(base);
FileInputStream in = new FileInputStream(f);
BufferedInputStream bi = new BufferedInputStream(in);
int b;
while ((b = bi.read()) != -1) {
bo.write(b); // 將字節流寫入當前zip目錄
}
bi.close();
in.close(); // 輸入流關閉
}
}
}