Java-a for compression and decompression (ZIP, gzip)

Source: Internet
Author: User
Tags crc32

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.

Note that Java comes with a tool class that cannot handle Chinese in Windows compression processing, so it is not recommended to use the JRE


Related classes and interfaces:

Checksum interface: Interfaces implemented by class Adler32 and CRC32 Adler32: Use Alder32 algorithm to calculate Checksum number CRC32: Use CRC32 algorithm to calculate Checksum number Checkedinputstream : InputStream derived class, you can get the checksum of the input stream checksum, used to verify the integrity of the data Checkedoutputstream:outputstream derived classes, you can get the checksum checksum of the output stream, Used to verify 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 of the decompression class Zipinputstream : A subclass of Inflaterinputstream that can decompress the data in the ZIP format Gzipinputstream:inflaterinputstream a subclass that can decompress the data in the ZIP format ZipEntry class: means zip File entry ZipFile class: This class is used to read entries from a ZIP file

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.

Test

 PackageCom.jre.util.zip;ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;Importjava.util.Enumeration;ImportJava.util.zip.ZipEntry;ImportJava.util.zip.ZipFile;ImportJava.util.zip.ZipInputStream;ImportJava.util.zip.ZipOutputStream;ImportCom.jre.io.UtilsIoJre;/*** ZIP file processing (compression processing when compressed by the Windows system because the encoding is not UTF8, so will cause the Chinese to throw an exception case) *@authorHuage **/ Public classUtilszipjre { Public Static voidMain (string[] args) {zipfileextract ("C:\\users\\huage\\desktop\\test\\111\\111.zip", "C:\\users\\huage\\desktop\\test\\test"); //zipdecompressingextract ("C:\\users\\huage\\desktop\\test\\111\\111.zip", "c:\\users\\huage\\desktop\\test\\        Test "); //zipcompressingextract ("C:\\users\\huage\\desktop\\test\\111\\test.zip", New File ("C:\\users\\huage\\desktop\ \test\\test "));    }        /*** Unzip *@paramPath *@parampathextract*/     Public Static voidzipfileextract (string path, String pathextract) {ZipFile ZipFile=NULL; Try{ZipFile=NewZipFile (path); Enumeration<ZipEntry> entries = (enumeration<zipentry>) zipfile.entries (); if(entries!=NULL) {ZipEntry entry;                  File file; Bufferedinputstream bis=NULL;  while(Entries.hasmoreelements ()) {entry=entries.nextelement (); if(Entry.isdirectory ())Continue; File=NewFile (Pathextract,entry.getname ()); if(!file.exists ()) {                          (NewFile (File.getparent ())). Mkdirs ();                    } utilsiojre.converwriteio (bis, file); //System.out.println (fout+ "decompression success");                 }            }        } Catch(IOException e) {e.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); } finally{Utilsiojre.closeio (ZipFile); }            }        /*** Zip decompression (local) (the official Zip decompression can not be processed in Chinese) * *@parampath *: Zip file Address *@paramPathextract *: Unzip address*/     Public Static voidzipdecompressingextract (string path, String pathextract) {Zipinputstream zipinput=NULL; Bufferedinputstream Bininput=NULL; Try{zipinput=NewZipinputstream (NewFileInputStream (path)); Bininput=NewBufferedinputstream (zipinput);            ZipEntry entry; File Fout=NULL;  while((Entry = Zipinput.getnextentry ())! =NULL) {                if(Entry.isdirectory ())Continue; Fout=NewFile (Pathextract,entry.getname ()); if(!fout.exists ()) {                      (NewFile (Fout.getparent ())). Mkdirs ();                } Utilsiojre.converwriteio (Bininput, fout); //System.out.println (fout+ "decompression success");             }        } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); } finally{Utilsiojre.closeio (bininput,zipinput); } System.out.println ("Decompression Complete"); }    /*** Zip compression (local) * *@paramZipfilename *@paramInputfile *@throwsException*/     Public Static voidzipcompressingextract (String zipfilename, File inputfile) {Zipoutputstream out=NULL; Bufferedoutputstream Bo=NULL; Try{ out=NewZipoutputstream (NewFileOutputStream (zipfilename)); Bo=NewBufferedoutputstream (out);        Zipcompressing (out, Inputfile, Bo); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); } finally{Utilsiojre.closeio (bo,out); } System.out.println ("Compression Complete"); }    /*** Zip compression * *@paramOut *@paramfile *@paramBase *@paramBo *@throwsException*/    Private Static voidZipcompressing (zipoutputstream out, file file, Bufferedoutputstream bo)throwsException {if(File.isdirectory ()) {file[] fl=File.listfiles (); if(Fl.length = = 0) {out.putnextentry (NewZipEntry (File.getname ())); }             for(inti = 0; i < fl.length; i++) {zipcompressing (out, Fl[i], bo); }        } Else{out.putnextentry (NewZipEntry (File.getname ()));        Utilsiojre.converreadio (bo, file); }    }} PackageCom.jre.io;ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;/*** IO Stream processing *@authorHuage **/ Public classUtilsiojre {/*** Write file to Bufferedoutputstream *@paramBo *@paramfile *@throwsException*/     Public Static voidConverreadio (Bufferedoutputstream bo,file File)throwsexception{FileInputStream in=Newfileinputstream (file); Bufferedinputstream Bi=NewBufferedinputstream (in); intb;  while((b = In.read ())! =-1) {bo.write (b);        } Closeio (Bi,in); Bo.flush ();//Empty Cache    }        /*** Write bufferedinputstream to file *@paramBo *@paramfile *@throwsException*/     Public Static voidConverwriteio (Bufferedinputstream bininput,file File)throwsexception{FileOutputStream out=Newfileoutputstream (file); Bufferedoutputstream bout=NewBufferedoutputstream (out); intb;  while((b = Bininput.read ())! =-1) {bout.write (b);        } Closeio (Bout,out); Bout.flush ();//Empty Cache    }            /*** Close IO *@paramCL*/     Public Static voidCloseio (autocloseable ... cl) {if(CL = =NULL|| Cl.length = = 0)return;  for(autocloseable c:cl) {Try{c.close (); } Catch(Exception e) {e.printstacktrace (); }        }    }}

Java-a for compression and decompression (ZIP, gzip)

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.