/**
 * Copyright 2002-2010 the original author is huanghe.
 */
package com.ucap.web.cm.webapp.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

import com.ucap.template.Constants;
import com.ucap.utils.UUIDGenerator;
import com.ucap.utils.formatString.FormatString;
import com.ucap.utils.formatString.Validator;

/**
 * 压缩和解压缩工具类
 */
@SuppressWarnings("unchecked")
public class ZipUtil {

private static int bufSize = 4096;
 private static byte[] buf = new byte[bufSize];

private static String OS_TYPE;
 static {
  if (System.getProperty("os.name").equals("Linux")) {
   OS_TYPE = "linux";
  } else if (System.getProperty("os.name").indexOf("Windows") != -1) {
   OS_TYPE = "windows";
  }
 }

public ZipUtil() {
 }

/**
  * 压缩文件夹内的文件
  *
  * @param zipDirectory
  *            需要压缩的文件夹名
  * @return File 压缩文件对象
  */
 public static File doZip(String zipDirectory) {
  ZipOutputStream zipOut;
  File zipDir = new File(zipDirectory);
  String zipFileName = zipDir.getName() + ".zip";// 压缩后生成的zip文件名
  if (System.getProperty("os.name").startsWith("Windows")) {
   if (!zipDirectory.endsWith("\\"))
    zipDirectory = zipDirectory + "\\";
  } else {
   if (!zipDirectory.endsWith("/"))
    zipDirectory = zipDirectory + "/";
  }

//判断压缩文件是否已经存在,如果存在则删除
  File preZip = new File(zipDirectory + "/" + zipFileName);
  if (preZip.exists()) {
   try {
    FileUtils.forceDelete(preZip);
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

//创建临时目录
  File tempFolder = createTempFolder();
  String tempPath = tempFolder.getAbsolutePath();

File zipFile = new File(tempPath + "/" + zipFileName);

if (!zipFile.getParentFile().exists())
   zipFile.getParentFile().mkdirs();
  if (zipFile.exists() && zipFile.canWrite())
   zipFile.delete();// 如果文件存在就删除原来的文件
  try {
   zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
   handleDir(zipOut, zipDir, "");
   zipOut.close();

FileUtils.copyFileToDirectory(zipFile, zipDir);

} catch (IOException ioe) {
   ioe.printStackTrace();

} finally {
   //删除临时文件夹
   if (tempFolder.exists()) {
    try {
     FileUtils.deleteDirectory(tempFolder);
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  File zip = new File(zipDir + "/" + zipFileName);
  return zip;
 }

/**
  * 由doZip调用,递归完成目录文件读取
  *
  */
 private static void handleDir(ZipOutputStream out, File f, String base) throws IOException {
  if (f.isDirectory()) {
   File[] fl = f.listFiles();
   if (System.getProperty("os.name").startsWith("Windows")) {
    base = base.length() == 0 ? "" : base + "\\";
    //out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
   } else {
    base = base.length() == 0 ? "" : base + "/";
    //out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
   }
   for (int i = 0; i < fl.length; i++) {
    handleDir(out, fl[i], base + fl[i].getName());
   }
  } else {
   out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
   FileInputStream in = new FileInputStream(f);
   byte b[] = new byte[512];
   int len = 0;
   while ((len = in.read(b)) != -1) {
    out.write(b, 0, len);
   }
   out.closeEntry();
   in.close();
  }
 }

/**
  * 解压指定zip文件
  *
  * @param unZipfileName
  *            需要解压的zip文件
  * @param destPath
  *            目录文件夹,如果目标文件夹为null ,则解压到当前目录下
  * @param isDeleteSrc
  *            是否删除原压缩文件
  * @throws Exception
  */
 public static List<String> unZip(File zipfileName, String destPath, boolean isDeleteSrc)
   throws Exception {
  List<String> ret = new ArrayList<String>();
  if (zipfileName == null)
   return ret;
  if (destPath == null)
   destPath = zipfileName.getAbsolutePath().substring(0,
     zipfileName.getAbsolutePath().lastIndexOf("\\"))
     + "\\";
  FileOutputStream fileOut;
  File file;
  InputStream inputStream;
  ZipFile zipFile;
  int readedBytes;
  File tempFolder = createTempFolder();
  String tempPath = tempFolder.getAbsolutePath();
  try {
     
      if (System.getProperty("os.name").equals("Linux"))
                zipFile = new org.apache.tools.zip.ZipFile(zipfileName,"GBK");
            else
                zipFile = new org.apache.tools.zip.ZipFile(zipfileName);
     
   for (Enumeration entries = zipFile.getEntries(); entries.hasMoreElements();) {
    ZipEntry entry = (ZipEntry) entries.nextElement();
    if (System.getProperty("os.name").equals("Linux"))
        entry.setUnixMode(644);//解决linux乱码
    file = new File(tempPath + "/" + entry.getName());
    if (entry.isDirectory()) {
     if (!file.exists())
      FileUtils.forceMkdir(file);
    } else {
     // 如果指定文件的目录不存在,则创建之.
     File parent = file.getParentFile();
     if (!parent.exists()) {
      FileUtils.forceMkdir(parent);
     }
     ret.add(entry.getName());
     inputStream = zipFile.getInputStream(entry);
     if (isRequiredSuffix(file.getAbsolutePath(), Constants.REQUIRED_ENCODE_SUFFIXS)) {
      String content = IOUtils.toString(inputStream, "UTF-8");
      FileUtils.writeStringToFile(file, content, "UTF-8");
     } else {
      fileOut = new FileOutputStream(file);
      while ((readedBytes = inputStream.read(buf)) > 0) {
       fileOut.write(buf, 0, readedBytes);
      }
      fileOut.close();
      inputStream.close();
     }
    }
   }
   zipFile.close();
   File destFolder = new File(destPath);
   if (!destFolder.exists()) {
    destFolder.mkdir();
   }
   FileUtils.copyDirectory(tempFolder, destFolder);

} catch (IOException ioe) {
   ioe.printStackTrace();
  } finally {
   //删除临时文件夹
   if (tempFolder.exists()) {
    try {
     FileUtils.deleteDirectory(tempFolder);
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   //删除上传的压缩文件
   if (isDeleteSrc)
    zipfileName.delete();
  }
  return ret;
 }

private static File createTempFolder() {
     File tempFolder = null;
     String tempPath = "";
     try{
      String tempFileName = UUIDGenerator.generate();
      if (OS_TYPE.equals("window"))
       tempPath = "C:/" + tempFileName;
      else
       tempPath = "/tmp/" + tempFileName;
         tempFolder = new File(tempPath);
      if (!tempFolder.exists()) {
       tempFolder.mkdir();
      }
     }catch (Exception e) {
            System.out.println("CreateTempFolder:"+tempPath +" Exception:" + e.getMessage());
        }
  return tempFolder;
 }

// 设置缓冲区大小
 public void setBufSize(int bufSize) {
  this.bufSize = bufSize;
 }

// 测试AntZip类
 public static void main(String[] args) throws Exception {
  ZipUtil m_zip = new ZipUtil();
  String filepath = "C:\\template\\template_upload/site/";
  try {
   m_zip.doZip(filepath);
  } catch (Exception ex) {
   ex.printStackTrace();
  }
 }

/**
  * 判断文件的后缀名是否包含在是否以suffixs中
  * @param fileName
  * @param suffixs
  * @return
  */
 public static boolean isRequiredSuffix(String fileName, String... suffixs) {
  if (Validator.isEmpty(fileName)) {
   return false;
  }
  if (suffixs == null || suffixs.length < 1) {
   return false;
  }
  for (String str : suffixs) {
   if (fileName.indexOf("." + str) == fileName.length() - ("." + str).length()) {
    return true;
   }
  }
  return false;
 }

/** 
  * 判断解压的文件是否包含汉字。
  *  
  * @param zipfileName 要解压的文件
  * @return    返回判断结果,true  含有 ;false 不含有
  */
 public static boolean isHaveChinese(File zipfileName) {
  ZipFile zipFile = null;
  try {
   zipFile = new ZipFile(zipfileName);
   ZipEntry zipEntry = null;
   Enumeration e = zipFile.getEntries();
   while (e.hasMoreElements()) {
    zipEntry = (ZipEntry) e.nextElement();
    if (FormatString.IsHaveChinese(zipEntry.getName())) {
     return true;
    }
   }
   return false;
  } catch (IOException e1) {
   e1.printStackTrace();
  } finally {
   try {
    zipFile.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return false;
 }
}

最新文章

  1. React Native之ListView使用
  2. GCD一些常用的方法
  3. 设置MyEclipse开发项目时使用的JDK
  4. leetcode 131. Palindrome Partitioning----- java
  5. Project Euler 82:Path sum: three ways 路径和:3个方向
  6. poj 3279 Fliptile
  7. java dubug调试
  8. 触发器内insert,delete,update判断执行不同的内容
  9. uva 11732 - strcmp() Anyone? 不错的Trie题
  10. 201521123016 《Java程序设计》第9周学习总结
  11. [Leetcode easy]存些水题34、20、700
  12. linux 学习笔记 finding people
  13. node起一个简单服务,打开本地项目或文件浏览
  14. [数据清洗]-Pandas 清洗“脏”数据(一)
  15. 【代码笔记】Web-ionic-安装及第一个app
  16. 快捷切换hosts的小工具:SwitchHosts!
  17. MD5加密与Hash加密
  18. 前端使用AngularJS的$resource,后端ASP.NET Web API,实现分页、过滤
  19. 【转载】TCP协议要点和难点全解
  20. Visual Basic 函数速查

热门文章

  1. 等价于n*n的矩阵,填写0,1,要求每行每列的都有偶数个1 (没有1也是偶数个),问有多少种方法。
  2. ScrollView的阻尼回弹效果实现(仿qq空间)
  3. linux的 压缩与解压 命令集
  4. 一个iOS6系统bug+一个iOS7系统bug
  5. NV12和NV21转rgb
  6. android EventBus 3.0使用指南
  7. SSH深度历险(十) AOP原理及相关概念学习+AspectJ注解方式配置spring AOP
  8. sublime text的Ctrl+alt+up快捷键失效问题解决
  9. Sharepoint2013部署ADFS 报new-sptrustedIdentityTokenIssuer:the trust provider certificate already exist
  10. Cookie 进阶