Java implementation zip compressed file (i)

Source: Internet
Author: User
Tags cos crc32

Online search for a long time, and finally found three kinds of good methods:

1, the JDK comes with the package java.util.zip.ZipOutputStream, the deficiency, the file (folder) name with Chinese,

There is a garbled problem, the implementation code is as follows:

/**
* Function: To compress all the files in the SourceDir directory in zip format, save as the specified zip file
* @param sourcedir If the directory, Eg:d:\\myeclipse\\first\\testfile, then compressed all the files in the directory;
* If it is a file, Eg:d:\\myeclipse\\first\\testfile\\aa.zip, only compress this file
* @param zipfile the last compressed file path and name, Eg:d:\\myeclipse\\first\\testfile\\aa.zip
*/
Public File Dozip (string sourcedir, String zipfilepath)
Throws IOException {

File File = new file (SourceDir);
File ZipFile = new file (Zipfilepath);
Zipoutputstream Zos = null;
try {
Create write Flow action
OutputStream OS = new FileOutputStream (ZipFile);
Bufferedoutputstream BOS = new Bufferedoutputstream (OS);
Zos = new Zipoutputstream (BOS);

String basepath = null;

Get directory
if (File.isdirectory ()) {
BasePath = File.getpath ();
}else {
BasePath = File.getparent ();
}

ZipFile (file, BasePath, Zos);
}finally {
if (Zos!= null) {
Zos.closeentry ();
Zos.close ();
}
}

return zipfile;
}

/**
* @param source file
* @param basepath
* @param Zos
*/
private void ZipFile (File source, String BasePath, Zipoutputstream Zos)
Throws IOException {
file[] files = null;
if (Source.isdirectory ()) {
Files = Source.listfiles ();
} else {
Files = new File[1];
Files[0] = source;
}

InputStream is = null;
String PathName;
byte[] buf = new byte[1024];
int length = 0;
try{
for (File file:files) {
if (File.isdirectory ()) {
PathName = File.getpath (). substring (basepath.length () + 1) + "/";
Zos.putnextentry (New ZipEntry (PathName));
ZipFile (file, BasePath, Zos);
}else {
PathName = File.getpath (). substring (basepath.length () + 1);
is = new FileInputStream (file);
Bufferedinputstream bis = new Bufferedinputstream (IS);
Zos.putnextentry (New ZipEntry (PathName));
while (length = Bis.read (buf)) > 0) {
Zos.write (buf, 0, length);
}
}
}
}finally {
if (is!= null) {
Is.close ();
}
}

}

2, the use of Org.apache.tools.zip.ZipOutputStream, code as follows, Java code:PackageNet.szh.zip;ImportJava.io.BufferedInputStream;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.util.zip.CRC32;ImportJava.util.zip.CheckedOutputStream;ImportOrg.apache.tools.zip.ZipEntry;ImportOrg.apache.tools.zip.ZipOutputStream; PublicclassZipcompressor {StaticFinalintBUFFER = 8192;PrivateFile ZipFile; PublicZipcompressor (String pathName) {ZipFile =NewFile (PathName); } PublicvoidCompress (String srcpathname) {File File =NewFile (Srcpathname);if(!file.exists ())ThrowNewRuntimeException (Srcpathname + "does not exist.) ");Try{FileOutputStream FileOutputStream =NewFileOutputStream (ZipFile); Checkedoutputstream cos =NewCheckedoutputstream (FileOutputStream,NewCRC32 ()); Zipoutputstream out =NewZipoutputstream (COS);                String basedir = "";                Compress (file, out, basedir);            Out.close (); }Catch(Exception e) {ThrowNewRuntimeException (e); }        }PrivatevoidCompress (file file, zipoutputstream out, String basedir) {/* To determine whether the directory or file */if(File.isdirectory ()) {System.out.println ("compression:" + Basedir + file.getname ()); This. compressdirectory (file, out, basedir); }Else{System.out.println ("compression:" + Basedir + file.getname ()); This. compressfile (file, out, basedir); }/** Compress a directory */PrivatevoidCompressdirectory (File dir, zipoutputstream out, String basedir) {if(!dir.exists ()) return; file[] files = dir.listfiles (); for(inti = 0; i < files.length;            i++) {* * recursive * * COMPRESS (files[i], out, Basedir + dir.getname () + "/"); }/** Compress a file */PrivatevoidCompressfile (file file, zipoutputstream out, String basedir) {if(!file.exists ()) { return; }Try{Bufferedinputstream bis =NewBufferedinputstream (NewFileInputStream (file)); ZipEntry entry =NewZipEntry (Basedir + file.getname ()); Out.putnextentry (entry);intCountbyteData[] =Newbyte[BUFFER]; while((count = bis.read (data, 0, BUFFER)!=-1)                {out.write (data, 0, count);            } bis.close (); }Catch(Exception e) {ThrowNewRuntimeException (e); }        }    }

3, can use Ant in the Org.apache.tools.ant.taskdefs.Zip to realize, more simple.
Java codePackageNet.szh.zip;ImportJava.io.File;ImportOrg.apache.tools.ant.Project;ImportOrg.apache.tools.ant.taskdefs.Zip;ImportOrg.apache.tools.ant.types.FileSet; Publicclasszipcompressorbyant {PrivateFile ZipFile; PublicZipcompressorbyant (String pathName) {ZipFile =NewFile (PathName); } PublicvoidCompress (String srcpathname) {File Srcdir =NewFile (Srcpathname);if(!srcdir.exists ())ThrowNewRuntimeException (Srcpathname + "does not exist.)                        "); Project PRJ =NewProject (); Zip zip =NewZip ();            Zip.setproject (PRJ);            Zip.setdestfile (ZipFile); Fileset Fileset =NewFileset ();            Fileset.setproject (PRJ);            Fileset.setdir (Srcdir); Fileset.setincludes ("**/*.java");            Include which files or folders eg:zip.setIncludes ("*.java"); Fileset.setexcludes (...);                        Exclude which files or folders zip.addfileset (Fileset);        Zip.execute (); }} Test
Java codePackageNet.szh.zip; PublicclassTestzip { PublicStaticvoidMain (string[] args) {Zipcompressor ZC =NewZipcompressor ("E:\\szhzip.zip");                        Zc.compress ("E:\\test"); Zipcompressorbyant Zca =NewZipcompressorbyant ("E:\\szhzipant.zip");        Zca.compress ("E:\\test"); }    }

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.