JAVA, using ant-1.6.5, compressing and decompressing auxiliary class code

Source: Internet
Author: User
Tags crc32

Sometimes, you need to do the file compression, decompression.

Java itself provides a compressed, uncompressed native class library. But with open source code, I generally choose to use the Open source class library.

Here's a sticker, I use ant-1.6.5 zip compression, unzip the code bar.

Ziputil.java
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.date;import Java.util.list;import Java.util.zip.crc32;import Org.apache.tools.ant.project;import Org.apache.tools.ant.taskdefs.expand;import Org.apache.tools.ant.taskdefs.zip;import Org.apache.tools.ant.types.fileset;import Org.apache.tools.ant.types.zipfileset;import Org.apache.tools.zip.zipentry;import Org.apache.tools.zip.ZipFile; Import org.apache.tools.zip.zipoutputstream;/** * <p> * Title: compression, decompression, auxiliary class * </p> * * @author mahh */public cl Ziputil {//==========================================================================//Compressed file method 1//============ ==============================================================/** * @Description: Compress a folder or a file * @param  Sourcefilepath * source folder or source file * @param destzip * Compressed zip file * @author mahh * @since: 2015-2-28 09:36:32 */public Static VoiD zip1 (String Sourcefilepath, String destzip) {fileutil.createparentfile (destzip);//The destination file does not exist create a project project = new P Roject (); Zip zip = new zip (), Zip.setproject (Project), Zip.setdestfile (New File (Destzip));//Set the generated destination zip file object Fileset Fileset = New Fileset (); Fileset.setproject (project); File SourceFile1 = new file (Sourcefilepath), if (Sourcefile1.isdirectory ()) {Fileset.setdir (SOURCEFILE1);// Sets the source file object that will be compressed//Fileset.setincludes ("**/*.java"); Which files or folders are included, only all Java files//fileset.setexcludes ("**/*.java") in the directory are compressed; Exclude which files or folders, compress all files, exclude Java files} else {fileset.setfile (sourceFile1);//Set the source file object that will be compressed}//add a fileset. Multiple Filesetzip.addfileset (Fileset) can be added in Zip, Zip.execute ();} /** * @Description: Unzip * @param sourcezipfilepath * Source Compressed file Zip * @param destzipdir * Unzip to folder path * @retu RN * @author mahh * @since: 2015-2-28 pm 04:57:28 */public static void UnZip1 (String sourcezipfilepath, String destzipdir) { Fileutil.createdir (Destzipdir); Project PROEJCT = new Project (); Expand Expand =New Expand (); Expand.setproject (PROEJCT); Expand.setsrc (new File (Sourcezipfilepath)); Expand.setoverwrite (false);// Whether overwrite//if not written, it is very likely that the file name of the extracted file (including Chinese) garbled expand.setencoding (System.getproperty ("sun.jnu.encoding")); File File = new file (destzipdir); expand.setdest (file); Expand.execute ();} ==========================================================================//Compressed file Method 2//======================== ==================================================/** * @Description: Compress a set of files into a compressed file * @param list * A set of compressed source files , file cannot be directory * @param destzipfilepath * Generate ZIP file absolute path * @param inzipbasepath * Compressed file within Zip, relative path (e.g. a/b/c), default in The zip root directory. * @return * @author mahh * @since: 2015-2-28 pm 05:09:33 */public static File zip2 (list<file> List, String destzipfile Path,string Inzipbasepath) {if (Inzipbasepath = = null) {Inzipbasepath = "";} Inzipbasepath = Buildfilepath (Inzipbasepath); File ZipFile = Fileutil.createnewfile (Destzipfilepath);//The destination file does not exist to create a zipoutputstream out = null;try {out =New Zipoutputstream (New FileOutputStream (ZipFile)); for (int i = 0; i < list.size (); i++) {File File = List.get (i); if (! File.exists ()) {continue;} if (File.isdirectory ()) {Dozipfolder (Inzipbasepath, out, file), or else {dozipfile (Inzipbasepath, out, file);}} return zipfile;} catch (IOException e) {throw new RuntimeException (e);} finally {Closezipoutstream (out);}} /** * @Description: Compresses only one folder itself (does not contain the contents of the folder) */private static void Dozipfolder (String inzipbasepath, zipoutputstream out, File file) throws IOException {zipentry ze = new ZipEntry (Inzipbasepath + fileutil.file_separator+ file.getname () + FileUt Il. File_separator); Ze.settime (new Date (). GetTime ()); ze.setsize (0); Ze.setmethod (zipentry.stored); ZE.SETCRC (New CRC32 (). GetValue ()); Ze.setunixmode (Zipfileset.default_dir_mode); Out.putnextentry (Ze);} /** * @Description: Compress a file */private static void Dozipfile (String inzipbasepath, zipoutputstream out,file file) throws IOE xception {FileInputStream in = new FileInputStream (file); Out.putnextentry (newZipEntry (Inzipbasepath + fileutil.file_separator+ File.getname ())); byte[] buf = new Byte[1024];int len;while (len = IN.R EAD (BUF)) > 0) {out.write (buf, 0, Len);} if (in = null) {In.close ();}} private static void Closezipoutstream (Zipoutputstream out) {if (out = = null) {return;} try {out.closeentry ();} catch (IOException e) {throw new RuntimeException (e);} try {out.close ();} catch (IOException e) {throw new RuntimeException (e);}} /** * @Description: Returns the string to remove the end of the \ or/* @param path * @return * @author mahh * @since: 2015-2-28 morning 10:36:31 */private static St Ring Buildfilepath (Final String path) {if (path = = null) {return "";} String retstr = Path;while (Fileutil.isfolderpath (RETSTR)) {if (Retstr.length () < 1) {break;} Retstr = retstr.substring (0, Retstr.length ()-1);} return RETSTR;} ==========================================================================//Extract File Method 2//======================= ===================================================/** * @Description: Unzip * @param sourcezipfilepath* Source Compressed file Zip * @param destzipdir * Unzip to Folder path * @return * @author mahh * @since: 2015-2-28 03:47:26 * * @SuppressWarnings ("unchecked") public static list<file> unZip2 (String sourcezipfilepath, String destzipdir) { list<file> res = new arraylist<file> (); ZipFile ZipFile = null;try {zipfile = new ZipFile (sourcezipfilepath);java.util.enumeration<zipentry> ele = ZipFile . GetEntries (); while (Ele.hasmoreelements ()) {ZipEntry ZipEntry = (zipentry) ele.nextelement (); File f = null;if (Fileutil.isfolderpath (Zipentry.getname ())) {//unzip a folder F = Dounzipfolder (Destzipdir, ZipFile, ZipEntry );} else {//unzip a file F = dounzipfile (Destzipdir, ZipFile, zipentry);} Res.add (f);}} catch (Exception e) {throw new RuntimeException ("{{not available zip file!}}");} finally {try {if (ZipFile! = null) {Zipfile.close ();} } catch (IOException e) {e.printstacktrace ();}} return res;} /** * @Description: Unzip a folder itself (does not contain the contents of the folder) */private static File Dounzipfolder (String destzipdir, ZipFile Zipfile,ziPentry zipentry) throws IOException {File f = fileutil.createnewfile (Destzipdir + fileutil.file_separator+ Zipentry.getname ()); return F;}  /** * @Description: Unzip a file */private static file Dounzipfile (String destzipdir, ZipFile zipfile,zipentry zipentry) throws IOException {File F = null;inputstream in = null; FileOutputStream out = null;try {f = fileutil.createnewfile (Destzipdir + fileutil.file_separator+ zipEntry.getName ()); in = Zipfile.getinputstream (zipentry), out = new FileOutputStream (f), byte[] by = new Byte[100000];int C;while (c = in.read (by)) ! =-1) {Out.write (by, 0, c);} Out.flush ();} catch (Exception e) {e.printstacktrace (); throw new RuntimeException (e);} finally {if (in = null) {in.close (); Close the input Stream object}if (out! = null) {out.close ();//////////////////////after decompression

Fileutil.java
Import Java.io.file;import java.io.ioexception;/** * <p> * Title: Create file, Folder Tool class * </p> * * @author mahh * */PUBL IC class Fileutil {/** * OS path separator */public static final String file_separator = System.getproperty ("File.separator");/** * @Description: Create a file (automatically create a folder where the path does not exist). * @param path * file paths * @return * @author mahh * @since: 2015-2-28 pm 02:23:29 */public static file CreateNewFile ( String path) {File File = new file (path);//If you end with a directory delimiter, then this path is a folder if (Isfolderpath (path)) {if (!file.exists ()) {file.mk Dirs ();} return file;} if (file.exists ()) {return file;} String Absolutepath = File.getabsolutepath ();//create file upper-level directory Createdir (absolutepath.substring (0, Absolutepath.lastindexof (File_separator)); try {//Create file File.createnewfile ();} catch (IOException e) { E.printstacktrace (); throw new RuntimeException ();} return file;} public static void Createparentfile (String path) {File File = new file (path); String Absolutepath = File.getabsolutepath ();//create File upper directory Createdir (absolutepath.substring (0, Absolutepath.lastindexof (File_separator)));} /** * @Description: Create folder * @param dir * @author mahh * @since: 2015-2-28 pm 02:23:40 */public static void Createdir (String Dir) {File file = new file (dir); if (!file.exists ()) {file.mkdirs ();}} /** * @Description: Determine if a string is not a folder path * @param path * @return * @author mahh * @since: 2015-2-28 morning 11:58:35 */public static B Oolean Isfolderpath (String path) {if (path = = null) {return false;} if (Path.endswith (File_separator)) {return true;} if (Path.endswith ("/")) {return true;} return false;}}





JAVA, using ant-1.6.5, compressing and decompressing auxiliary class code

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.