java压缩文件夹

来源:互联网 发布:余秋雨散文怎么样知乎 编辑:程序博客网 时间:2024/05/22 05:20

package compress;
import java.io.*;
import java.util.zip.*;
public class CompressFolder {
 private static ZipOutputStream   zos;
 public  void compressOneFolder(String fromPath,String toPath){
    String name = "";
    name = fromPath.substring(fromPath.lastIndexOf("//"))+".zip";
    File file = new File(toPath+"//"+name);
     try {
   zos = new ZipOutputStream(new CheckedOutputStream(new FileOutputStream(file),new CRC32()));
   recurseFile(new File(fromPath));
   try {
    zos.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
   }
   private void recurseFile(File file){//递归
    if(file.isDirectory()){
     String[] fileNames = file.list();
     if(fileNames!=null){
      for(int i=0;i<fileNames.length;i++){
       recurseFile(new File(file,fileNames[i]));
      }
     }
    }else{
      byte[] buf = new byte[1024];    
      int len;     
      ZipEntry zipEntry = new ZipEntry(file.toString());    
      FileInputStream fin;
    try {
    fin = new FileInputStream(file);
         BufferedInputStream in = new BufferedInputStream(fin);    
         zos.putNextEntry(zipEntry);       
         while((len = in.read(buf))>=0)   {    
           zos.write(buf,0,len);    
         }       
         in.close();       
         zos.closeEntry();
        
     } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
     } 
          
    }
    
   }
}