对文件目录进行压缩为zip包

 [[178884]]

 
 
  1. import java.io.File; 
  2. import java.io.FileInputStream; 
  3. import java.io.FileOutputStream; 
  4. import java.util.zip.ZipOutputStream; 
  5.  
  6. /** 
  7. * 实现对文件目录进行压缩为zip包 
  8. * Created by zyb on 7月31日. 
  9. */ 
  10. public class Compressor { 
  11.  /** 
  12.  
  13.  * @param inputFileName 输入一个文件夹 //"c:\\15统计报表" 
  14.  * @param zipFileName 输出一个压缩文件夹,打包后文件名字 //"D:\\Program Files\\/21bstzxReport.zip"; //压缩后的zip文件 
  15.  * @throws Exception 
  16.  */ 
  17.  public void zip(String inputFileName, String zipFileName) throws Exception { 
  18.  // System.out.println(zipFileName); 
  19.  zip(zipFileName, new File(inputFileName)); 
  20.  } 
  21.  private void zip(String zipFileName, File inputFile) throws Exception { 
  22.  ZipOutputStream out = new ZipOutputStream(new FileOutputStream( 
  23.  
  24.  zipFileName)); 
  25.  zip(out, inputFile, ""); 
  26.  out.closeEntry(); 
  27.  out.close(); 
  28.  } 
  29.  private void zip(ZipOutputStream out, File f, String base) throws Exception { 
  30.  if (f.isDirectory()) { //判断是否为目录 
  31.  File[] fl = f.listFiles(); 
  32.  
  33.  out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/")); 
  34.  base = base.length() == 0 ? "" : base + "/"
  35.  for (int i = 0; i < fl.length; i++) { 
  36.  zip(out, fl[i], base + fl[i].getName()); 
  37.  } 
  38.  } else { //压缩目录中的所有文件 
  39.  out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); 
  40.  FileInputStream in = new FileInputStream(f); 
  41.  int b; 
  42.  // System.out.println(base); 
  43.  while ((b = in.read()) != -1) { 
  44.  out.write(b); 
  45.  } 
  46.  in.close(); 
  47.  } 
  48.  } 

【本文是专栏作者张勇波的原创文章,转载请通过获取作者授权】

THE END