Using ant to implement zip compression and decompression (i)

Source: Internet
Author: User
There are many ways to compress files, most commonly using util tools and ant tools. The difference is that the Util tool cannot set the encoding format of the file, and the Ant tool can customize the file encoding.
The following is compressed and decompressed via the Ant tool

1. First look at the compression process, directly look at the code: Ziputil.

<span style= "FONT-SIZE:12PX;"

>package Com.ilucky.zip;
Import Java.io.BufferedInputStream;
Import Java.io.BufferedOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;

Import java.io.IOException;
Import Org.apache.tools.zip.ZipEntry;

Import Org.apache.tools.zip.ZipOutputStream;
	
	/** * @author Iluckysi * @date 20140531/public class Ziputil {public String code;
	
	public int buffer;
	
	Public String Srcpath;
	
	Public String Dstpath;
	Public String GetCode () {return code;
	public void Setcode (String code) {this.code = code;
	public int GetBuffer () {return buffer;
	public void SetBuffer (int buffer) {this.buffer = buffer;
	Public String Getsrcpath () {return srcpath;
	} public void Setsrcpath (String srcpath) {this.srcpath = Srcpath;
	Public String Getdstpath () {return dstpath;
	} public void Setdstpath (String dstpath) {this.dstpath = Dstpath;
		public void Startzip () {Boolean next = true;
				if (Srcpath). exists () = = False) {try {next = false; throw new Exception ("source path + Srcpath +" does not exist.)
			");
			catch (Exception e) {e.printstacktrace ();
		} String dstdir = dstpath.substring (0, Dstpath.lastindexof ("/"));
				if (Dstdir). exists () = = False) {try {next = false; throw new Exception ("Target path" + Dstdir +) does not exist.
			");
			catch (Exception e) {e.printstacktrace ();
		} if (next = = False) {return;
		} File zip = null;
		FileOutputStream fos = null;
		Bufferedoutputstream BOS = NULL;
		Zipoutputstream Zos = null;
			try {zip = new File (Dstpath);
			FOS = new FileOutputStream (Zip);
			BOS = new Bufferedoutputstream (FOS);
			Zos = new Zipoutputstream (BOS);
			Zos.setencoding (code);
		Generatezip (Srcpath, Zos);
		catch (Exception e) {System.out.println (e.tostring ());
					Finally {try {if (Zos!= null) {zos.closeentry ();
					Zos.close ();
				Zos = null; } if (Bos!= null) {Bos.close ();
				BOS = NULL;
					} if (fos!= null) {fos.close ();
				FOS = null;
			The catch (IOException e) {System.out.println (e.tostring ());
		}} public void Generatezip (String filePath, Zipoutputstream zos) {File File = new file (FilePath);
		file[] files = null;
			try {if (File.isdirectory ()) {files = File.listfiles ();
				else if (File.isfile ()) {files = new file[1];
			Files[0] = file;
				for (int i = 0; files!= null && i < files.length; i++) {//Critical: Zip node file name.
				String fileName = Files[i].getpath (). substring (Srcpath.lastindexof ("/") + 1);
					if (Files[i].isdirectory ()) {System.out.println ("Start compressed directory" + Files[i].getpath ());
					Zos.putnextentry (New ZipEntry (FileName + "/"));
				Generatezip (Files[i].getpath (), Zos);
					else {FileInputStream FIS = null;
					Bufferedinputstream bis = null;
						try {System.out.println ("Start compressed file" + Files[i].getpath ()); Zos.putnextentry (New ZiPentry (FileName));
						FIS = new FileInputStream (files[i]);
						bis = new Bufferedinputstream (FIS);
						byte[] bytes = new Byte[buffer];
						int length = 0;
							while (length = bis.read (bytes, 0, buffer))!=-1) {zos.write (bytes, 0, length);
						Zos.flush ();
					The catch (Exception e) {System.out.println (e.tostring ());
								Finally {try {if (bis!= null) {bis.close ();
							bis = null;
								} if (FIS!= null) {fis.close ();
							FIS = null;
						The catch (IOException e) {System.out.println (e.tostring ());
		catch (Exception e) {System.out.println (e.tostring ()); }} </span>

In the compression process, the key is to get the node name of the compressed file, Files[i].getpath (). substring (Srcpath.lastindexof ("/") + 1), that is, the use of LastIndexOf.
The second is to set the encoding format for GB2312, otherwise there will be garbled Chinese.

2. Then look at the decompression process, directly look at the code: Unziputil.

<span style= "FONT-SIZE:12PX;"

>package Com.ilucky.zip;
Import Java.io.BufferedInputStream;
Import Java.io.BufferedOutputStream;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;

Import java.util.Enumeration;
Import Org.apache.tools.zip.ZipEntry;

Import Org.apache.tools.zip.ZipFile;
	 
	/** * @author Iluckysi * @date 20140531/public class Unziputil {public String code;
	
	public int buffer;
	
	Public String Srcpath;
	
	Public String Dstpath;
	Public String GetCode () {return code;
	public void Setcode (String code) {this.code = code;
	public int GetBuffer () {return buffer;
	public void SetBuffer (int buffer) {this.buffer = buffer;
	Public String Getsrcpath () {return srcpath;
	} public void Setsrcpath (String srcpath) {this.srcpath = Srcpath;
	Public String Getdstpath () {return dstpath;
	} public void Setdstpath (String dstpath) {this.dstpath = Dstpath; } @SuppresSwarnings ("rawtypes") public void Startunzip () {Boolean next = true;
				if (Srcpath). exists () = = False) {try {next = false; throw new Exception ("source path + Srcpath +" does not exist.)
			");
			catch (Exception e) {e.printstacktrace ();
				} if (new File (Dstpath). exists () = = False) {try {next = false; throw new Exception ("Target path" + Dstpath +) does not exist.
			");
			catch (Exception e) {e.printstacktrace ();
		} if (next = = False) {return;
		} ZipFile zipfile = null; 
			try {zipfile = new ZipFile (Srcpath, code);
			Enumeration EMU = Zipfile.getentries ();
				while (Emu.hasmoreelements ()) {InputStream is = null;
				Bufferedinputstream bis = null;
				FileOutputStream fos = null;
				Bufferedoutputstream BOS = NULL;
					try {zipentry entry = (zipentry) emu.nextelement ();
						if (!entry.isdirectory ()) {File File = new file (Dstpath + "/" + entry.getname ());
						System.out.println ("Start creating uncompressed File" + File.getpath ()); is = Zipfile.getinPutstream (entry);
						bis = new Bufferedinputstream (IS);
						Key: Create a parent file, Mkdirs is to create a multi-tiered directory.
						File parent = File.getparentfile ();
							if (parent!= null && (!parent.exists ())) {parent.mkdirs ();
						System.out.println ("Start to create uncompressed directory" + Parent.getpath ());
						FOS = new FileOutputStream (file);
						BOS = new Bufferedoutputstream (fos, buffer);
						byte[] buf = new Byte[buffer];
						int length = 0;
							while (length = Bis.read (buf, 0, buffer))!=-1) {bos.write (buf, 0, length);
						Bos.flush ();
				A catch (Exception e) {System.out.println (e.tostring ());
							Finally {try {if (Bos!= null) {bos.close ();
						BOS = NULL;
							} if (fos!= null) {fos.close ();
						FOS = null;
							} if (bis!= null) {bis.close ();
						bis = null;
							} if (is!= null) {is.close ();
						is = null; The catch (IOException e) {System.out.println (e.tostring());
		catch (Exception e) {System.out.println (e.tostring ()); }}}</span>

In the decompression process, the key is how to create a multi-tiered directory, that is, the difference between mkdir (creating a tier of directories) and mkdirs (creating a multi-tiered directory).
The second is to set the encoding format for GB2312, otherwise there will be garbled Chinese.

3. Finally, the compression process and decompression process are validated by the test program. Look directly at the code: maintest.

<span style= "FONT-SIZE:12PX;"

>package Com.ilucky.zip; /** * @author Iluckysi * @date 20140531/public class Maintest {public static void main (string[] args) {//Will be
		A directory/file under the directory is compressed into a specified directory.
		Ziputil ziputil = new Ziputil ();
		Ziputil.setcode ("GB2312");
		Ziputil.setbuffer (10240);
		Ziputil.setsrcpath ("e:/src/src");//If the file must have a suffix.
		Ziputil.setdstpath ("E:/dst/src.zip");
		Long startzip = System.currenttimemillis ();
		Ziputil.startzip ();
		Long endzip = System.currenttimemillis ();
		
		SYSTEM.OUT.PRINTLN ("Compressed file time consuming:" + (Endzip-startzip) + "milliseconds");
		Unzip a compressed file in a directory to a specified directory.
		Unziputil unziputil = new Unziputil ();
		Unziputil.setcode ("GB2312");
		Unziputil.setbuffer (10240);
		Unziputil.setsrcpath ("E:/src/src.zip");
		Unziputil.setdstpath ("E:/dst");
		Long startunzip = System.currenttimemillis ();
		Unziputil.startunzip ();
		Long endunzip = System.currenttimemillis ();
	SYSTEM.OUT.PRINTLN ("Decompression file time consuming:" + (Endunzip-startunzip) + "millisecond"); }} </span>
The source and destination paths are separated by a forward slash during the test, otherwise there will be a problem.

Click on the link to download source and Ant.jar

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.