Use Java base classes to implement ZIP compression and zip decompression tool class sharing _java

Source: Internet
Author: User
Tags zip

A simple zip compression decompression Tool class written using Java base classes

Copy Code code as follows:



Package sun.net.helper;

Import java.io.*;
Import Java.util.logging.Logger;
Import java.util.zip.*;

public class Ziputil {
Private final static Logger Logger = Logger.getlogger (ZipUtil.class.getName ());
private static final int BUFFER = 1024*10;

/**


* Compress the specified directory into a zip file with the same name as the directory, and customize the compression path


* @param sourcefilepath destination file path


* @param zipfilepath Specify zip file path


* @return


*/


public static Boolean zip (String sourcefilepath,string zipfilepath) {


Boolean result=false;


File Source=new file (Sourcefilepath);


if (!source.exists ()) {


Logger.info (sourcefilepath+ "doesn ' t exist.");


return result;


}


if (!source.isdirectory ()) {


Logger.info (sourcefilepath+ "is not a directory.");


return result;


}


File Zipfile=new file (zipfilepath+ "/" +source.getname () + ". zip");


if (zipfile.exists ()) {


Logger.info (Zipfile.getname () + "is already exist.");


return result;


}else{


if (!zipfile.getparentfile (). exists ()) {


if (!zipfile.getparentfile (). Mkdirs ()) {


Logger.info ("Cann ' t create file" +zipfile.getname ());


return result;


}


}


}


Logger.info ("Creating zip file ...");


FileOutputStream Dest=null;


Zipoutputstream out =null;


try {


Dest = new FileOutputStream (ZipFile);


Checkedoutputstream checksum = new Checkedoutputstream (dest, New Adler32 ());


Out=new Zipoutputstream (new Bufferedoutputstream (checksum));


Out.setmethod (zipoutputstream.deflated);


Compress (Source,out,source.getname ());


Result=true;


catch (FileNotFoundException e) {


E.printstacktrace ();


}finally {


if (out!= null) {


try {


Out.closeentry ();


catch (IOException e) {


E.printstacktrace ();


}


try {


Out.close ();


catch (IOException e) {


E.printstacktrace ();


}


}


}


if (result) {


Logger.info ("done.");


}else{


Logger.info ("fail.");


}


return result;


}


private static void Compress (File file,zipoutputstream out,string mainfilename) {


if (File.isfile ()) {


FileInputStream fi= null;


Bufferedinputstream Origin=null;


try {


fi = new FileInputStream (file);


Origin=new Bufferedinputstream (FI, BUFFER);


int Index=file.getabsolutepath (). IndexOf (Mainfilename);


String Entryname=file.getabsolutepath (). substring (index);


System.out.println (EntryName);


ZipEntry entry = new ZipEntry (entryname);


Out.putnextentry (entry);


byte[] data = new Byte[buffer];


int count;


while (count = origin.read (data, 0, BUFFER)!=-1) {


Out.write (data, 0, count);


}


catch (FileNotFoundException e) {


E.printstacktrace ();


catch (IOException e) {


E.printstacktrace ();


}finally {


If (Origin!= null) {


try {


Origin.close ();


catch (IOException e) {


E.printstacktrace ();


}


}


}


}else if (file.isdirectory ()) {


File[] Fs=file.listfiles ();


if (fs!=null&&fs.length>0) {


for (File F:fs) {


Compress (F,out,mainfilename);


}


}


}


}

/**


* Extract the zip file to the specified directory, which must be a compressed file using the Zip method of the class


* @param zipfile


* @param destpath


* @return


*/


public static Boolean unzip (File zipfile,string DestPath) {


Boolean result=false;


if (!zipfile.exists ()) {


Logger.info (Zipfile.getname () + "doesn ' t exist.");


return result;


}


File Target=new file (destpath);


if (!target.exists ()) {


if (!target.mkdirs ()) {


Logger.info ("Cann ' t create file" +target.getname ());


return result;


}


}


String mainfilename=zipfile.getname (). Replace (". zip", "");


File Targetfile=new file (destpath+ "/" +mainfilename);


if (targetfile.exists ()) {


Logger.info (Targetfile.getname () + "already exist.");


return result;


}


Zipinputstream ZiS =null;


Logger.info ("Start unzip file ...");


try {


FileInputStream fis= New FileInputStream (ZipFile);


Checkedinputstream checksum = new Checkedinputstream (FIS, New Adler32 ());


ZiS = new Zipinputstream (new Bufferedinputstream (checksum));


ZipEntry entry;


while ((entry = Zis.getnextentry ())!= null) {


int count;


byte data[] = new Byte[buffer];


String Entryname=entry.getname ();


int Index=entryname.indexof (mainfilename);


String newentryname=destpath+ "/" +entryname.substring (index);


System.out.println (Newentryname);


File Temp=new file (newentryname). Getparentfile ();


if (!temp.exists ()) {


if (!temp.mkdirs ()) {


throw new RuntimeException ("Create File" +temp.getname () + "fail");


}


}


FileOutputStream fos = new FileOutputStream (newentryname);


Bufferedoutputstream dest = new Bufferedoutputstream (fos,buffer);


while (count = zis.read (data, 0, BUFFER)!=-1) {


Dest.write (data, 0, count);


}


Dest.flush ();


Dest.close ();


}


Result=true;


catch (FileNotFoundException e) {


E.printstacktrace ();


catch (IOException e) {


E.printstacktrace ();


}finally {


if (ZiS!= null) {


try {


Zis.close ();


catch (IOException e) {


E.printstacktrace ();


}


}


}


if (result) {


Logger.info ("done.");


}else{


Logger.info ("fail.");


}


return result;


}


public static void Main (string[] args) throws IOException {


Ziputil.zip ("d:/apache-tomcat-7.0.30", "d:/temp");


File Zipfile=new file ("D:/temp/apache-tomcat-7.0.30.zip");


Ziputil.unzip (ZipFile, "d:/temp");


}


}








Another example of compression decompression, two tools for everyone to refer to the use of it

Copy Code code as follows:



Package COM.LANP;

Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.util.zip.ZipEntry;
Import java.util.zip.ZipException;
Import Java.util.zip.ZipFile;
Import Java.util.zip.ZipInputStream;

/**


* Extract Zip Compressed file to specified directory


*/


Public final class Ziptofile {


/**


* Buffer size Default 20480


*/


Private final static int file_buffer_size = 20480;





Private Ziptofile () {





}





/**


* Extract Zip Compressed files from the specified directory to the specified directory


* @param zipfilepath Zip compressed file path


* @param zipfilename Zip compressed file name


* @param targetfiledir Zip Compressed files to be extracted to the directory


* @return Flag Boolean return value


*/


public static Boolean unzip (string Zipfilepath, String zipfilename, String targetfiledir) {


Boolean flag = false;


1. Determine if the compressed file exists, and whether the contents are empty


File file = null; Compressed file (with path)


ZipFile zipfile = null;


File = new File (Zipfilepath + "/" + zipfilename);


System.out.println (">>>>>> Extract File" "+ Zipfilepath +"/"+ Zipfilename +" "to" + Targetfiledir + "" "Directory <&L t;<<<< ");


if (false = = File.exists ()) {


SYSTEM.OUT.PRINTLN (">>>>>> Compressed file" "+ Zipfilepath +"/"+ Zipfilename +" "No <<<<<<") ;


return false;


else if (0 = file.length ()) {


SYSTEM.OUT.PRINTLN (">>>>>> Compressed file" "+ Zipfilepath +"/"+ Zipfilename +" "Size 0 does not require decompression <<<<< < ");


return false;


} else {


2. Start decompression Zip compressed file processing


byte[] buf = new Byte[file_buffer_size];


int readsize =-1;


Zipinputstream zis = null;


FileOutputStream fos = null;


try {


Check if it is a zip file


ZipFile = new ZipFile (file);


Zipfile.close ();


To determine if the target directory exists or not, create


File Newdir = new file (Targetfiledir);


if (false = = Newdir.exists ()) {


Newdir.mkdirs ();


Newdir = null;


}


ZiS = new Zipinputstream (new FileInputStream (file));


ZipEntry zipentry = Zis.getnextentry ();


Start processing files in a compressed package


while (null!= zipentry) {


String zipentryname = Zipentry.getname (). replace (' \ n ', '/');


Determine if the zipentry is a directory, and if so, create


if (Zipentry.isdirectory ()) {


int indexnumber = Zipentryname.lastindexof ('/');


File Entrydirs = new file (Targetfiledir + "/" + zipentryname.substring (0, IndexNumber));


Entrydirs.mkdirs ();


Entrydirs = null;


} else {


try {


FOS = new FileOutputStream (Targetfiledir + "/" + zipentryname);


while ((ReadSize = Zis.read (buf, 0, file_buffer_size))!=-1) {


Fos.write (buf, 0, readsize);


}


catch (Exception e) {


E.printstacktrace ();


throw new RuntimeException (E.getcause ());


finally {


try {


if (null!= fos) {


Fos.close ();


}


catch (IOException e) {


E.printstacktrace ();


throw new RuntimeException (E.getcause ());


}


}


}


ZipEntry = Zis.getnextentry ();


}


Flag = true;


catch (Zipexception e) {


E.printstacktrace ();


throw new RuntimeException (E.getcause ());


catch (IOException e) {


E.printstacktrace ();


throw new RuntimeException (E.getcause ());


finally {


try {


if (null!= zis) {


Zis.close ();


}


if (null!= fos) {


Fos.close ();


}


catch (IOException e) {


E.printstacktrace ();


throw new RuntimeException (E.getcause ());


}


}


}


return flag;


}

/**
* The Main method for testing
*/
public static void Main (string[] args) {
String Zipfilepath = "C:\\home";
String zipfilename = "Lp20120301.zip";
String Targetfiledir = "c:\\home\\lp20120301";
Boolean flag = Ziptofile.unzip (Zipfilepath, Zipfilename, Targetfiledir);
if (flag) {
System.out.println (">>>>>> decompression success <<<<<<");
} else {
System.out.println (">>>>>> decompression failure <<<<<<");
}
}

}

Related Article

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.