天天看點

Zip操作的工具類



/**

 * 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 + "/";

   for (int i = 0; i < fl.length; i++) {

    handledir(out, fl[i], base + fl[i].getname());

   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;

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

   //删除上傳的壓縮檔案

   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/";

   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) {

  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;

   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;

  } catch (ioexception e1) {

   e1.printstacktrace();

    zipfile.close();

}

繼續閱讀