- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.util.zip.ZipOutputStream;
- /**
- * 实现对文件目录进行压缩为zip包
- * Created by zyb on 7月31日.
- */
- public class Compressor {
- /**
- * @param inputFileName 输入一个文件夹 //"c:\\15统计报表"
- * @param zipFileName 输出一个压缩文件夹,打包后文件名字 //"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专栏作者张勇波的原创文章,转载请通过51CTO获取作者授权】