Tool classes for ZIP operations

Source: Internet
Author: User

??

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

/**
* Compression and Decompression tool class
*/
@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 () {
}

 /**
  * Compress files within a folder
  *
  * @param zipdirectory
  *             folder names that need to be compressed
  * @return File Compressed Files Object
  */
 public Static File Dozip (String zipdirectory) {
  zipoutputstream zipout;
  file Zipdir = new File (zipdirectory);
  string zipfilename = zipdir.getname () + ". Zip",//ZIP file name generated after compression
  if (System.getproperty ( "Os.name"). StartsWith ("Windows") {
   if (!zipdirectory.endswith ("\ \"))
     zipdirectory = zipdirectory + "\ \";
  } else {
   if (!zipdirectory.endswith ("/"))
     Zipdirectory = zipdirectory + "/";
  }

Determine if the compressed file already exists and delete if it exists
File Prezip = new file (zipdirectory + "/" + zipfilename);
if (prezip.exists ()) {
try {
Fileutils.forcedelete (Prezip);
} catch (IOException e) {
E.printstacktrace ();
}
}

Create a temp directory
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 ()//Delete the original file if it exists
try {
ZipOut = new Zipoutputstream (new Bufferedoutputstream (New FileOutputStream (ZipFile)));
Handledir (ZipOut, Zipdir, "");
Zipout.close ();

Fileutils.copyfiletodirectory (ZipFile, Zipdir);

} catch (IOException IoE) {
Ioe.printstacktrace ();

} finally {
Delete Temp Folder
if (tempfolder.exists ()) {
try {
Fileutils.deletedirectory (TempFolder);
} catch (IOException e) {
E.printstacktrace ();
}
}
}
File Zip = new file (Zipdir + "/" + zipfilename);
return zip;
}

/**
* Called by Dozip, recursively completes directory file read
*
*/
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 ();
}
}

/**
* Unzip the specified zip file
*
* @param unzipfilename
* ZIP file required for decompression
* @param destpath
* Directory folder, if the destination folder is null, unzip to the current directory
* @param isdeletesrc
* Whether to delete the original compressed file
* @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);//Solve Linux garbled
File = new File (TempPath + "/" + entry.getname ());
if (Entry.isdirectory ()) {
if (!file.exists ())
Fileutils.forcemkdir (file);
} else {
If the directory for the specified file does not exist, it is created.
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 {
Delete Temp Folder
if (tempfolder.exists ()) {
try {
Fileutils.deletedirectory (TempFolder);
} catch (IOException e) {
E.printstacktrace ();
}
}
Delete an uploaded compressed file
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;
}

Set Buffer size
public void setbufsize (int bufSize) {
This.bufsize = bufSize;
}

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

/**
* Determine if the suffix of the file is included in 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;
}

/**
* Determine if the extracted files contain Chinese characters.
*
* @param zipfilename files to unzip
* @return return judgment result, true contains; false does not contain
*/
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;
}
}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Tool classes for ZIP operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.