package com.chenyang.nse.bussiness.tools.zip;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnZipUtils {
   public static final String EXT = ".zip";
   private static final String BASE_DIR = "";
   private static final String PATH;
   private static final int BUFFER = 1024;

   public static void decompress(String srcPath) throws Exception {
      File srcFile = new File(srcPath);
      decompress(srcFile);
   }

   public static void decompress(File srcFile) throws Exception {
      String basePath = srcFile.getParent();
      decompress(srcFile, basePath);
   }

   public static void decompress(File srcFile, File destFile) throws Exception {
      CheckedInputStream cis = new CheckedInputStream(new FileInputStream(srcFile), new CRC32());
      ZipInputStream zis = new ZipInputStream(cis, Charset.forName("GBK"));
      decompress(destFile, zis);
      zis.close();
   }

   public static void decompress(File srcFile, String destPath) throws Exception {
      decompress(srcFile, new File(destPath));
   }

   public static void decompress(String srcPath, String destPath) throws Exception {
      File srcFile = new File(srcPath);
      decompress(srcFile, destPath);
   }

   private static void decompress(File destFile, ZipInputStream zis) throws Exception {
      ZipEntry entry;
      for(entry = null; (entry = zis.getNextEntry()) != null; zis.closeEntry()) {
         String dir = destFile.getPath() + File.separator + entry.getName();
         File dirFile = new File(dir);
         fileProber(dirFile);
         if (entry.isDirectory()) {
            dirFile.mkdirs();
         } else {
            decompressFile(dirFile, zis);
         }
      }

   }

   private static void fileProber(File dirFile) {
      File parentFile = dirFile.getParentFile();
      if (!parentFile.exists()) {
         fileProber(parentFile);
         parentFile.mkdir();
      }

   }

   private static void decompressFile(File destFile, ZipInputStream zis) throws Exception {
      BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
      byte[] data = new byte[1024];

      int count;
      while((count = zis.read(data, 0, 1024)) != -1) {
         bos.write(data, 0, count);
      }

      bos.close();
   }

   public static void main(String[] args) throws Exception {
      decompress("D:\\home\\ghca\\data\\测试a.zip", "D:\\home\\ghca\\data\\aa\\");
   }

   static {
      PATH = File.separator;
   }
}
