對(duì)文件目錄進(jìn)行壓縮為zip包
作者:張勇波
博主發(fā)表的文章,有的是自己原創(chuàng),有的是這些年本人從網(wǎng)上積累的,方便大家學(xué)習(xí)。
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.util.zip.ZipOutputStream;
- /**
- * 實(shí)現(xiàn)對(duì)文件目錄進(jìn)行壓縮為zip包
- * Created by zyb on 7月31日.
- */
- public class Compressor {
- /**
- * @param inputFileName 輸入一個(gè)文件夾 //"c:\\15統(tǒng)計(jì)報(bào)表"
- * @param zipFileName 輸出一個(gè)壓縮文件夾,打包后文件名字 //"D:\\Program Files\\/21bstzxReport.zip"; //壓縮后的zip文件
- * @throws Exception
- */
- public void zip(String inputFileName, String zipFileName) throws Exception {
- // System.out.println(zipFileName);
- zip(zipFileName, new File(inputFileName));
- }
- private void zip(String zipFileName, File inputFile) throws Exception {
- ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
- zipFileName));
- zip(out, inputFile, "");
- out.closeEntry();
- out.close();
- }
- private void zip(ZipOutputStream out, File f, String base) throws Exception {
- if (f.isDirectory()) { //判斷是否為目錄
- File[] fl = f.listFiles();
- out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
- base = base.length() == 0 ? "" : base + "/";
- for (int i = 0; i < fl.length; i++) {
- zip(out, fl[i], base + fl[i].getName());
- }
- } else { //壓縮目錄中的所有文件
- out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
- FileInputStream in = new FileInputStream(f);
- int b;
- // System.out.println(base);
- while ((b = in.read()) != -1) {
- out.write(b);
- }
- in.close();
- }
- }
- }
【本文是51CTO專欄作者張勇波的原創(chuàng)文章,轉(zhuǎn)載請(qǐng)通過51CTO獲取作者授權(quán)】
責(zé)任編輯:武曉燕
來源:
上下求索的Z先生博客