Tool class (ant-1.8.4.jar) for compressing and decompressing files)

Source: Internet
Author: User
Tags crc32 deflater

Use the org.apache.tools.zip package in ant-1.8.4.jarto compress and decompress files. The following classes are used in the jar package:

Org.apache.tools.zip. zipentry;
Org.apache.tools.zip. zipfile;
Org.apache.tools.zip. zipoutputstream;

Is:

Http://ant.apache.org/

The following is a tool class for compressing and decompressing files I have written, with a test attached. Please debug it for me:

Import Java. io. bufferedinputstream; import Java. io. bufferedoutputstream; import Java. io. file; import Java. io. fileinputstream; import Java. io. filenotfoundexception; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. util. arraylist; import Java. util. enumeration; import Java. util. list; import java.util.zip. CRC32; import java.util.zip. checkedoutputstream; import java.util.zip. deflater; import Java.util.zip. zipexception; import org.apache.tools.zip. zipentry; import org.apache.tools.zip. zipfile; import org.apache.tools.zip. zipoutputstream;/*** @ Description: * compression and decompression tool */public class ziputil {/*** @ description: * compressed file * @ Param sourcepath: Path of the file or directory to be compressed. Use absolute path * @ Param zippath to generate the path of the compressed file. Use absolute path. If the region ends with ". Zip", * indicates the name of the compressed file. If the region does not end with ". Zip, the name of the compressed file is * COMPRESSED "and ends with * @ Param encoding compression encoding * @ Param comment compression annotation */public static void compress (string sourcepath, string zippath, string encoding, string comment) throws filenotfoundexception, ioexception {// determine whether the file to be compressed exists file sourcefile = new file (sourcepath); If (! Sourcefile. exists () | (sourcefile. isdirectory () & sourcefile. list (). length = 0) {Throw new filenotfoundexception ("the file or directory to be compressed does not exist, or the directory to be compressed is blank");} // set the path of the compressed file, by default, the parent directory of the path to be compressed is the parent directory of the compressed file if (zippath = NULL | "". equals (zippath) {string sourcepathname = sourcefile. getabsolutepath (); int Index = sourcepathname. lastindexof (". "); zippath = (index>-1? Sourcepathname. substring (0, index): sourcepathname) + ". Zip";} If (! Zippath. endswith (". zip ") {// if the path to be compressed is the directory, the directory name is used to compress the file name. If the path to be compressed is the file, the file name is used to remove the extension) for the compressed file name string filename = sourcefile. getname (); int Index = filename. lastindexof (". "); zippath = zippath + file. separator + (index>-1? Filename. substring (0, index): Filename) + ". zip ";}}// set the extract encoding if (encoding = NULL | "". equals (encoding) {encoding = "GBK";} // if the parent directory of the compressed file to be created does not exist, create file zipfile = new file (zippath); If (! Zipfile. getparentfile (). exists () {zipfile. getparentfile (). mkdirs () ;}// create a compressed file output stream fileoutputstream Fos = NULL; try {Fos = new fileoutputstream (zippath);} catch (filenotfoundexception e) {If (FOS! = NULL) {try {FOS. close () ;}catch (exception E1) {}}// use the specified checksum to create the output stream checkedoutputstream csum = new checkedoutputstream (FOS, new CRC32 ()); // create a compressed stream zipoutputstream ZOS = new zipoutputstream (csum); // sets the encoding and supports Chinese ZOS. setencoding (encoding); // set the compressed package to comment on zOS. setcomment (comment); // enable ZOS compression. setmethod (zipoutputstream. deflated); // sets the compression level to the strongest compression ZOS. setlevel (Deflater. best_compression); // compressed file Buffer stream bufferedoutputstream Bou T = NULL; try {// encapsulate the compressed stream as the buffer stream bout = new bufferedoutputstream (ZOS); // compressrecursive (ZOS, bout, sourcefile, sourcefile. getparent ();} finally {If (bout! = NULL) {try {bout. close () ;}catch (exception e) {}}}/*** @ Description: * compressed file, supports compressing multiple files or directories to the same compressed file * @ Param sourcepath: a set of paths of the files or directories to be compressed, use the absolute path * @ Param zippath to generate the path of the compressed file. Use the absolute path. This path cannot be empty, and ends with "pai.zip" * @ Param encoding compression encoding * @ Param comment compression annotation */public static void compress (list <string> sourcepaths, string zippath, string encoding, string comment) throws filenotfoundexception, ioexception {// sets the compressed file path. By default, the parent directory of the path to be compressed is the parent directory of the compressed file. If (zippath = NULL | "". equals (zippath) |! Zippath. endswith (". zip ") {Throw new filenotfoundexception (" specify a compression class, and the compression class ends with '.zip '");} // you can set the extract encoding if (encoding = NULL | "". equals (encoding) {encoding = "GBK";} // if the parent directory of the compressed file to be created does not exist, create file zipfile = new file (zippath); If (! Zipfile. getparentfile (). exists () {zipfile. getparentfile (). mkdirs () ;}// create a compressed file output stream fileoutputstream Fos = NULL; try {Fos = new fileoutputstream (zippath);} catch (filenotfoundexception e) {If (FOS! = NULL) {try {FOS. close () ;}catch (exception E1) {}}// use the specified checksum to create the output stream checkedoutputstream csum = new checkedoutputstream (FOS, new CRC32 ()); // create a compressed stream zipoutputstream ZOS = new zipoutputstream (csum); // sets the encoding and supports Chinese ZOS. setencoding (encoding); // set the compressed package to comment on zOS. setcomment (comment); // enable ZOS compression. setmethod (zipoutputstream. deflated); // sets the compression level to the strongest compression ZOS. setlevel (Deflater. best_compression); // compressed file Buffer stream bufferedoutputstream Bou T = NULL; try {// encapsulate the compressed stream as the buffer stream bout = new bufferedoutputstream (ZOS); // iteratively compress each path for (INT I = 0, Len = sourcepaths. size (); I <Len; I ++) {// obtain the file sourcefile = new file (sourcepaths. get (I); // compressrecursive (ZOS, bout, sourcefile, sourcefile. getparent () ;}} finally {If (bout! = NULL) {try {bout. close () ;}catch (exception e) {}}}/*** @ Description: * When compressing a file, the used Iteration Method * @ Param ZOS compresses the output stream * @ Param bout encapsulates the buffer stream of the compressed output stream * @ Param sourcefile path of the file or directory to be compressed * @ Param prefixdir the entire parent directory of the file or directory to be compressed, input this value to get the name of the compression entry */Private Static void compressrecursive (zipoutputstream ZOS, bufferedoutputstream bout, file sourcefile, string prefixdir) throws ioexception, filenotfoundexception {// get the name, chu The relative path string entryname = sourcefile of the file or directory to be compressed at the beginning. getabsolutepath (). substring (prefixdir. length () + file. separator. length (); // determine whether it is a file or a directory. If it is a directory, continue to iteratively compress if (sourcefile. isdirectory () {// if it is a directory, you need to add a separator ('/') after the directory // zipentry = new zipentry (entryname + file. separator); // ZOS. putnextentry (zipentry); // obtain the files in the directory and iteratively compress the file [] srcfiles = sourcefile. listfiles (); For (INT I = 0; I <srcfiles. length; I ++ ){/ /Compressrecursive compression (ZOS, bout, srcfiles [I], prefixdir );}} else {// start writing new zip file entries and locate the stream to the beginning of the entry data zipentry = new zipentry (entryname ); // write a new entry ZOS to the compressed stream. putnextentry (zipentry); // read the input stream bufferedinputstream bin = NULL for the file to be compressed; try {// get the input stream to read the file bin = new bufferedinputstream (New fileinputstream (sourcefile )); // read the file and write the compressed stream byte [] buffer = new byte [1024]; int readcount =-1; while (readcount = bin. rea D (buffer ))! =-1) {bout. write (buffer, 0, readcount);} // Note: when using a buffer stream to write a compressed file, you must refresh the file after one condition is complete, otherwise, some contents may be saved to the bout in the subsequent entries. flush (); // close the current ZIP entry and locate the stream to write to the next entry ZOS. closeentry ();} finally {If (bin! = NULL) {try {bin. close () ;}catch (ioexception e) {}}}/ *** @ Description: * decompress the file * @ Param zippath is compressed, use the absolute path * @ Param targetpath to decompress the path. The extracted files will be placed in this directory, use the absolute path * the parent directory of the compressed file path by default is the decompression path * @ Param encoding decompress encoding */public static void decompress (string zippath, string targetpath, string encoding) throws filenotfoundexception, zipexception, ioexception {// get the decommission file = new file (zippath); If (! File. isfile () {Throw new filenotfoundexception ("the file to be decompressed does not exist");} // set the decompression path if (targetpath = NULL | "". equals (targetpath) {targetpath = file. getparent () ;}// set the extract encoding if (encoding = NULL | "". equals (encoding) {encoding = "GBK";} // instantiate the zipfile object zipfile = new zipfile (file, encoding ); // obtain the entry enumeration <zipentry> files = zipfile in zipfile. getentries (); // zipentry entry = NULL in each iteration; // decompressed File OUTFILE = NULL; // read the compressed file input stream bufferedinputstream bin = NULL; // write the compressed file output stream bufferedoutputstream bout = NULL; while (files. hasmoreelements () {// obtain the extract entry = files. nextelement (); // instantiate and decompress the file object OUTFILE = new file (targetpath + file. separator + entry. getname (); // If the entry is a directory, it will jump to the next if (entry. getname (). endswith (file. separator) {OUTFILE. mkdirs (); continue;} // create the directory if (! OUTFILE. getparentfile (). exists () {OUTFILE. getparentfile (). mkdirs ();} // create a new file named OUTFILE. createnewfile (); // if it cannot be written, it will jump to the next entry if (! OUTFILE. canwrite () {continue;} Try {// get the input stream bin = new bufferedinputstream (zipfile. getinputstream (entry); // get the output stream bout = new bufferedoutputstream (New fileoutputstream (OUTFILE) of the decompressed file; // read the entry, and write the file byte [] buffer = new byte [1024]; int readcount =-1; while (readcount = bin. read (buffer ))! =-1) {bout. write (buffer, 0, readcount) ;}} finally {try {bin. close (); bout. flush (); bout. close () ;}catch (exception e) {}}} public static void main (string [] ARGs) throws exception {// compresstest (); // compresstest2 (); // decompresstest ();} public static void compresstest () throws exception {string sourcepath = "E:" + file. separator + "document" + file. separator + "Music"; string zippath = "E:" + file. separator + "My music .zip"; string comment = "Music compressed file"; compress (sourcepath, zippath, "GBK", comment);} public static void decompresstest () throws exception {string zippath = "E:" + file. separator + "My music .zip"; string targetpath = "E:" + file. separator + "Temp"; decompress (zippath, targetpath, "GBK");} public static void compresstest2 () throws exception {list <string> List = new arraylist <string> (); list. add ("E:" + file. separator + "document" + file. separator + "Music"); list. add ("E:" + file. separator + "document" + file. separator + "video"); list. add ("E:" + file. separator + "document" + file. separator + ""); list. add ("E:" + file. separator + "document" + file. separator + "books"); string zippath = "E:" + file. separator + "My document compressed file. Zip"; string comment = "My document compressed file"; compress (list, zippath, "GBK", comment );}}

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.