生成Zip文件

生成Zip文件

package com.pdw.datastruts;

import java.io.*;
import org.apache.tools.ant.*;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class ZipDemo {

 public ZipDemo() { 
 }
   /**
    *
    * @param inputFileName
    */
 public void Zip(String inputFileName)throws Exception {
  String targetFile="c:/abc.zip";
  System.out.println("output zip file name->"+targetFile);
  Zip(targetFile,new File(inputFileName));
 }
 
 public void Zip(String zipFileName,File inputFile)throws Exception {
  ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipFileName));
  Zip(out,inputFile,"");
  System.out.println("zip done ");
  out.close();
 }
 
 public void Zip(ZipOutputStream out,File f,String base)throws Exception{
  if(f.isDirectory()) {
   File[] ary_f=f.listFiles();
   out.putNextEntry(new ZipEntry(base+"/"));
   base=base.length()==0?"":base+"/";
   for(int i=0;i<ary_f.length;i++) {
    Zip(out,ary_f[i],base+ary_f[i].getName());
   }
  }else {
   out.putNextEntry(new ZipEntry(base));
   FileInputStream in=new FileInputStream(f);
   int b;
   System.out.println(base);
   while((b=in.read())!=-1) {
    out.write(b);
   }
   in.close();
  }
 }
 
 public static void main(String[] args) {
  ZipDemo zipDemo=new ZipDemo();
  try {
   zipDemo.Zip("C:\\z");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

你可能感兴趣的:(生成Zip文件)