Java implementation of file compression and decompression

Source: Internet
Author: User
Tags crc32

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. (Reproduced from http://www.puiedu.com/applyOnline_daily_news.php?id=68 nantong Java Training)

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 interface: Interfaces implemented by class Adler32 and CRC32
Adler32: Using the ALDER32 algorithm to calculate the number of checksum
CRC32: Using the CRC32 algorithm to calculate the number of checksum

Checkedinputstream:inputstream derived classes that provide checksum checksum of the input stream for verifying the integrity of the data
Checkedoutputstream:outputstream derived classes that obtain checksum checksum of the output stream for verifying the integrity of the data

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

Inflaterinputstream: The base class for the decompression class
A subclass of Zipinputstream:inflaterinputstream that can decompress data in a ZIP format
A subclass of Gzipinputstream:inflaterinputstream that can decompress data in a 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 support for the ZIP Format Class Library is more comprehensive, it can be used to compress multiple files into a 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.

Class ZipEntry describes the compressed files stored in a 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 more than the interface to set the encoding, 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:

package gizaction;import java.io.*;import java.util.zip.*;/** *  @author  dana· The li * <p> *  program implements the ZIP compression [compression] * <p> *  roughly functions including 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  */public class ZipCompressing {     private int k = 1; //  define recursive number of variables     private  void zip (String zipfilename, file inputfile)  throws Exception {         system.out.println ("in compression ...");         zipoutputstream out = new zipoutputstream (New fileoutputstream ( Zipfilename));         bufferedoutputstream bo = new  bufferedoutputstream (out);         zip (oUt, inputfile, inputfile.getname (),  bo);         Bo.close ();         out.close (); //  output stream off     &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("compression complete");    }     Private void zip (zipoutputstream out, file f, string base,   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;BUFFEREDOUTPUTSTREAM&NBSP;BO)  throws  exception { //  method overload         if  (F.isdirectory ()) {             file[] fl = f.listfiles ();            if  (fl.length == 0) {                  Out.putnextentry (New zipentry (base +  " /")); //  Create a 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 (" + k +  sub-recursion");             k++;        } else {             out.putnextentry (New zipentry (base)); //  Create a zip compression entry point base             system.out.println (Base);             fileinputstream in = new fileinputstream (f );             bufferedinputstream bi =  new bufferedinputstream (in);             int b;            while  (b =  bi.read ())  != -1)  {                 bo.write (b); //  writes a byte stream to the current zip directory              }             Bi.close ();    &nbSp;        in.close (); //  input stream off          }    }    /**     *   Testing      *  @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:

Package gizaction;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.zip.zipentry;import  java.util.zip.zipinputstream;/** *  @author  dana li * <p> *  program to achieve the ZIP decompression [decompression] * <p> *  approximate functions including 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; */ public class zipdecompressing  {      public static void main (String[] args)  {           // todo auto-generated method stub           long starttime=system.currenttimemillis ();           try {               zipinputstream zin=new zipinputstream (New FileInputStream (                         "F:ziptest.zip"));//input source Zip path                bufferedinputstream bin=new bufferedinputstream (Zin);               string parent= "F:ziptest";  / /Output path (folder directory)               file fout =null;              zipentry entry;               try {                    while (Entry = zin.getnextentry () )!=null && !entry.isdirectory ()) {                       fout=new file (Parent, Entry.getname ());                       if (! Fout.exists ()) {                            (New file (Fout.getparent ())). Mkdirs ();                        }                       fileoutputstream out=new fileoutputstreAM (Fout);                       bufferedoutputstream bout=new bufferedoutputstream (out);                        int b;                       while ((B=bin.read ())!=-1) {                            bout.write (b);                       }                       bout.close ();        &nBsp;              out.close ();                        system.out.println (fout+ "unzip successfully");                       }                   bin.close ();                   zin.close ();               } catch  (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.

import java.io.bufferedoutputstream;import java.io.bufferedreader;import  java.io.fileinputstream;import java.io.fileoutputstream;import java.io.ioexception;import  Java.io.inputstreamreader;import java.util.zip.gzipinputstream;import java.util.zip.gzipoutputstream ;p Ublic class gzipcompress {    public static void main ( String[] args)  throws ioexception {        // Do prepare to compress a character file, note that the character file here if GBK encoded         bufferedreader in =  new bufferedreader (New inputstreamreader (New fileinputstream (                  "E:/tmp/source.txt"),  "GBK");         //uses Gzipoutputstream to wrap the outputstream flow, making its specific compression characteristics, Finally, the test.txt.gz compression package is generated         //andThe polygon has a file named Test.txt         bufferedoutputstream out = new  bufferedoutputstream (New gzipoutputstream (                 new fileoutputstream ("test.txt.gz"));         system.out.println ("Start writing Compressed Files ...");         int  c;        while  ((C = in.read ())  != -1)  {            /*               *  Note, here is the compression of a character file, preceded by a stream of characters to read, can not be directly deposited in C, Because C is already a unicode             *  code, This will lose the information (of course, the encoding format is not correct), so here to GBK to the solution and then deposit.              */      &nbsP;      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 with the decompression feature         BufferedReader  In2 = new bufferedreader (New inputstreamreader (                 new gzipinputstream (New FileInputStream (" Test.txt.gz ")), " GBK ");        string s;         //reads the contents of the compressed file         while  (s  = in2.readline ())  != null)  {             system.out.println (s);         }        in2.close ();     }}

Java implementation file compression and decompression

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.