Java implementation file compression and decompression [ZIP format, gzip format]

Source: Internet
Author: User
Tags crc32 create zip

Java implementation Zip decompression and compression is basically using the Java peptide and recursive technology, can be a single file and any Cascade folder compression and decompression, for some beginners is a good example.

Zip plays archive and compresses two roles; gzip does not archive files, only compresses individual files, so on UNIX platforms, command tar is typically used to create an archive file and then command gzip to compress the archive file. The Java I/O class Library also includes classes that read and write compressed format streams. To provide compression, just wrap them outside the existing I/O class. These classes are not reader and writer, but subclasses of InputStream and Outstreamput. This is because the compression algorithm is for byte rather than character. Related classes and interfaces: Checksum Interfaces: interfaces implemented by class Adler32 and CRC32 Adler32 : Use Alder32 algorithm to calculate Checksum number CRC32 : Using the CRC32 algorithm to calculate the number of checksum

checkedinputstream : InputStream derived class that can obtain checksum checksum of the input stream for verifying the integrity of the data Checkedoutputstream : OutputStream derived class for checksum checksum of the output stream for verifying the integrity of the data

Deflateroutputstream : The base class for the compression class. Zipoutputstream : A subclass of Deflateroutputstream that compresses the data into a ZIP file format. Gzipoutputstream : A subclass of Deflateroutputstream that compresses data into gzip file format

Inflaterinputstream : The base class of the decompression class Zipinputstream : A subclass of Inflaterinputstream that can decompress data in the ZIP format Gzipinputstream : A subclass of Inflaterinputstream that can decompress data in zip format

ZipEntry class: Represents a ZIP file entry ZipFile class: This class is used to read entries from a zip file

Compress and decompress multiple files using zip

Java supports the ZIP format class Library in a comprehensive way, so that it can compress multiple files into a single compressed package. This class library uses the standard ZIP format, so it can be compatible with a number of compression tools. The Zipoutputstream class has a compression method set and the compression level used in compression, and Zipoutputstream.setmethod (int method) sets the default compression method for entries. As long as no compression method is specified for a single ZIP file entry, the compression method set by Zipoutputstream is used to store the default value Zipoutputstream.deflated (for compressed storage), can also be set to stored (which means that only the archive storage is packaged). Zipoutputstream after setting the compression method to deflated, we can further use the setlevel (int level) method to set the compression level, the compression levels value is 0-9 a total of 10 levels (the greater the value, the more the compression is more interested), The default is Deflater.default_compression=-1. Of course we can also set the compression method for a single condition by using the Setmethod method of the entry zipentry. The
Class ZipEntry describes the compressed files stored in the zip file. The class contains information that can be used to set and get a zip entry. The class ZipEntry is used by Zipfile[zipfile.getinputstream (ZipEntry entry)] and zipinputstream to read the zip file, zipoutputstream to write to the zip file. Here are some useful methods: GetName () returns the entry name, Isdirectory () if it is a directory entry, returns True (the directory entry is defined as an entry whose name ends with '/'), Setmethod (int method) Sets the entry's compression method, which can be assumed Zipoutputstream.stored or Zipoutputstream. Deflated.

The following example we used the Apache ZIP Toolkit (the package is Ant.jar ), because the Java type comes with the Chinese path is not supported, but the use of the same way, but the Apache compression tool is more than the interface to set the encoding method, The others are basically the same. Other than that If we use Org.apache.tools.zip.ZipOutputStream to compress, we can only use org.apache.tools.zip.ZipEntry to decompress, but cannot use Java.util.zip.ZipInputStream to decompress Read, and of course Apache does not provide the Zipinputstream class.

File compression:

PackageGizaction;Import java.io.*;Import java.util.zip.*;/***@authorDana Li * <p> * program implemented ZIP compression [compression] * <p> * Approximate features include the use of polymorphic, recursive and other Java core technology, can be a single file and any Cascade folder compression and decompression. You need to customize the source input path and the target output path in your code. * <p> * In this section of the Code, the implementation of the compression section*/PublicClasszipcompressing {Privateint k = 1;//Defining recursive number variablesPrivatevoid Zip (String zipfilename, File inputfile)ThrowsException {System.out.println ("in compression ..."); Zipoutputstream out =New Zipoutputstream (NewFileOutputStream (Zipfilename)); Bufferedoutputstream bo =NewBufferedoutputstream (out); Zip (out, Inputfile, Inputfile.getname (), Bo); Bo.close (); Out.close ();//Output stream off System.out.println ("Compression Done"); }PrivatevoidZip (Zipoutputstream out, File F, String Base, Bufferedoutputstream bo)Throws Exception {//Method overloadingIf(F.isdirectory ()) {file[] fl =F.listfiles ();if (Fl.length = = 0) {Out.putnextentry (New ZipEntry (base + "/"));//Create Zip compression entry point base System.out.println (base + "/"); }for (int i = 0; i < fl.length; i++) {Zip (out, fl[i], base + "/" + Fl[i].getname (), Bo);//Recursively traverse subfolders} System.out.println ("nth" + K + "secondary recursion"); k++; }Else{Out.putnextentry (New ZipEntry (base));//Create a ZIP compression entry point baseSystem.out.println (base); FileInputStream in =NewFileInputStream (f); Bufferedinputstream bi =NewBufferedinputstream (in);Intbwhile ((b = Bi.read ())! =-1) {Bo.write (b);//Writes a stream of bytes to the current zip directory} bi.close (); In.close ();// input stream close }} /** * Test * @param args */public   static void main (string[] args) {zipcompressing book = new zipcompressing (); try {book.zip ("F:\\ziptest.zip",new File ("F:\\ziptest")); Catch (Exception e) {e.printstacktrace ();          }}} 

File decompression:

PackageGizaction;ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileNotFoundException;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.util.zip.ZipEntry;ImportJava.util.zip.ZipInputStream;/***@authorDana Li * <p> * program for ZIP decompression [decompression] * <p> * Approximate features include the use of polymorphic, recursive and other Java core technology, can be a single file and any Cascade folder compression and decompression. You need to customize the source input path and the target output path in your code. * <p> * In this section of the code, the implementation is the decompression section;*/PublicClasszipdecompressing {PublicStaticvoidMain (string[] args) {//TODO auto-generated Method StubLong starttime=System.currenttimemillis ();Try{Zipinputstream zin=New Zipinputstream (NewFileInputStream ("F:\\ziptest.zip"));//Input source zip path Bufferedinputstream bin=NewBufferedinputstream (Zin); String parent= "f:\\ziptest\\";//Output path (folder directory) File fout=Null; ZipEntry entry;Try{while ((entry = Zin.getnextentry ())! =Null &&!Entry.isdirectory ()) {fout=NewFile (Parent,entry.getname ());if (!Fout.exists ()) {(NewFile (Fout.getparent ())). Mkdirs (); } FileOutputStream out=New FileOutputStream (Fout); Bufferedoutputstream bout=new Bufferedoutputstream ( Out); int b; while ((B=bin.read ())!=-1catch (IOException e) {e.printstacktrace ();}} catch (FileNotFoundException e) {e.printstacktrace ();} long endtime=system.currenttimemillis (); SYSTEM.OUT.PRINTLN ("Time Consuming:" + (Endtime-starttime) + "MS" 

use gzip to compress individual files

The gzip interface is simple, so you can use it if you only need to compress a stream. Of course it can compress the character stream, and can compress the byte stream, the following is a GBK encoded format of the text file compression. The usage of the compression class is very simple, as long as the output stream is wrapped up with gzipoutputstream or Zipoutputstream, and then the input stream is wrapped with gzipinputstream or zipinputstream. All that is left is normal I/O operations.

ImportJava.io.BufferedOutputStream;ImportJava.io.BufferedReader;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.util.zip.GZIPInputStream;ImportJava.util.zip.GZIPOutputStream;PublicClassgzipcompress {PublicStaticvoid Main (string[] args)ThrowsIOException {//Do prepare to compress a character file, note that the character file here if GBK encoded bufferedreader in =New BufferedReader (New InputStreamReader (NewFileInputStream ("E:/tmp/source.txt"), "GBK"));//Use Gzipoutputstream to wrap the OutputStream stream so that it specifically compresses the properties, resulting in a test.txt.gz compression package//And there is a file named Test.txt bufferedoutputstream out =New Bufferedoutputstream (NewGzipoutputstream (New FileOutputStream ("test.txt.gz"))); System.out.println ("Start writing Compressed Files ...");IntCwhile ((c = In.read ())! =-1) {/** Note, here is the compression of a character file, the front is a character stream to read, can not be directly deposited in C, because C is already Unicode * code, this will throw away information (of course, the encoding format is not correct), so here to GBK to the solution and then deposit.*/Out.write (String.valueof (char) c). GetBytes ("GBK")); } in.close (); Out.close (); System.out.println ("Start reading Compressed files ..."); // use Gzipinputstream to wrap the InputStream stream so that it has decompression characteristics bufferedreader in2 = new BufferedReader (new  InputStreamReader (New gzipinputstream (new FileInputStream ("test.txt.gz")), "GBK"); String s;  Read the contents of the compressed file while ((s = in2.readline ()) = null) {SYSTEM.OUT.PRINTLN (s);} in2.close ();}} 

Resources:

http://www.oschina.net/code/snippet_12_259

http://blog.csdn.net/kevin_luan/article/details/7903400

http://jiangzhengjun.iteye.com/blog/517186

Java implementation file compression and decompression [ZIP format, gzip format]

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.