java压缩文件夹

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       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();
     } 
          
    }
    
   }
}

你可能感兴趣的:(IO)