java压缩文件/文件夹的方法

package snippet;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**

* 文件压缩(支持中文文件名)

* @author zhaochao

*

*/

public class FileHelper {

 public static void zipCompress(String src, String des) throws IOException {
  ZipOutputStream out = null;
  try {
   CheckedOutputStream cusm = new CheckedOutputStream( new FileOutputStream(des), new Adler32());
   out = new ZipOutputStream(new BufferedOutputStream(cusm));

   fileZip(new File(src), out, "");
  } finally {
   if (out != null) {
    out.close();
   }
  }
 }

 private static void fileZip(File file, ZipOutputStream out, String base)
   throws IOException {
  if (file.isFile()) {
   if (base.length() > 0) {
    out.putNextEntry(new ZipEntry(base));
   } else {
    out.putNextEntry(new ZipEntry(file.getName()));
   }

   BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "ISO8859_1"));

   int c;
   while ((c = in.read()) != -1) {
    out.write(c);
   }
   in.close();

  } else if (file.isDirectory()) {
   File[] subFiles = file.listFiles();

   out.putNextEntry(new ZipEntry(base + File.separator));
   base = base.length() != 0 ? base + File.separator : "";

   for (File subFile : subFiles) {
    fileZip(subFile, out, base + subFile.getName());
   }
  }

 }
 
 public static void main(String[] args) throws IOException {
     /*需要压缩的源文件夹路径*/  

    String folderSrcPath="E:\\TEMP\\";  

    /*压缩后的zip文件及其存放位置*/

     String forderDesPath="E:\\测试文件夹.zip"; 
     zipCompress(folderSrcPath,forderDesPath);
    
 }
}

你可能感兴趣的:(java,apache,C++,c,C#)