Java.util.zip Compression and Decompression tool class

Source: Internet
Author: User

The Java.util.zip provides classes for reading and writing standard zip and GZIP file formats.

It also includes classes that compress and decompress data using the DEFLATE compression algorithm (for ZIP and GZIP file formats).

Relying on the JDK to write the tool class, do not rely on any third-party jar, with the fetch, the implementation of the following functions:

1. Directory-level recursive compression and decompression zip;

2. Single file compression and decompression zip;

ImportJava.io.*;ImportJava.util.zip.ZipEntry;ImportJava.util.zip.ZipInputStream;ImportJava.util.zip.ZipOutputStream;/*** Compression and decompression files via Java's zip input/output stream*/ Public Final classZiputil {PrivateZiputil () {}/*** Zip file * *@paramfilePath file path to be compressed *@returnthe compressed file*/     Public Staticfile Zip (String filePath) {file target=NULL; File Source=NewFile (FilePath); if(Source.exists ()) {String SourceName=Source.getname (); String Zipname= Sourcename.contains (".")? Sourcename.substring (0, Sourcename.indexof ("."))): SourceName; Target=NewFile (Source.getparent (), Zipname + ". rar"); if(Target.exists ()) {BooleanDelete = Target.delete ();//Delete Old compressed package} fileoutputstream Fos=NULL; Zipoutputstream Zos=NULL; Try{fos=NewFileOutputStream (target); Zos=NewZipoutputstream (Newbufferedoutputstream (FOS)); AddEntry (NULL, source, Zos);//Add the corresponding file entry}Catch(IOException e) {Throw NewRuntimeException (e); } finally{ioutil.closequietly (Zos, FOS); }        }        returnTarget; }    /*** Scan Add File entry * *@paramBase Base Path *@paramSource file *@paramzos zip file output stream *@throwsIOException*/    Private Static voidAddEntry (String base, File source, Zipoutputstream Zos)throwsIOException {String entry= (Base! =NULL) ? Base + source.getname (): Source.getname ();//classified by directory, shape: Aaa/bbb.txt        if(Source.isdirectory ()) {file[] files=Source.listfiles (); if(Files! =NULL&& files.length > 0) {                 for(File file:files) {addentry (entry+ "/", file, Zos);//recursively lists all files in the directory, adding files Entry                }            }        } Else{FileInputStream fis=NULL; Bufferedinputstream bis=NULL; Try {                byte[] buffer =New byte[1024 * 10]; FIS=NewFileInputStream (source); Bis=Newbufferedinputstream (FIS, buffer.length); intRead; Zos.putnextentry (NewZipEntry (entry));//If you just want to compress all the files under the folder, do not need the name to compress the parent directory, the contract filename length entry.substring (length)                 while(read = bis.read (buffer, 0, buffer.length))! =-1) {zos.write (buffer,0, read);            } zos.closeentry (); } finally{ioutil.closequietly (bis, FIS); }        }    }    /*** Unzip the file * *@paramFilePath Compressed file path*/     Public Static voidUnzip (String filePath) {File source=NewFile (FilePath); if(Source.exists ()) {Zipinputstream ZiS=NULL; Bufferedoutputstream Bos=NULL; Try{ZiS=NewZipinputstream (NewFileInputStream (source));                ZipEntry entry;  while((Entry = Zis.getnextentry ())! =NULL&&!entry.isdirectory ()) {File target=NewFile (Source.getparent (), Entry.getname ()); if(!Target.getparentfile (). exists ()) {  target.getparentfile (). Mkdirs (); }BOS =NewBufferedoutputstream (NewFileOutputStream (target)); intRead; byte[] buffer =New byte[1024 * 10];  while(read = zis.read (buffer, 0, buffer.length))! =-1) {bos.write (buffer,0, read);                } bos.flush ();            } zis.closeentry (); } Catch(IOException e) {Throw NewRuntimeException (e); } finally{ioutil.closequietly (ZiS, BOS); }        }    }}

Input/Output tool class Ioutil:

Importjava.io.Closeable;Importjava.io.IOException;/*** IO stream Tool class*/ Public classIoutil {/*** Close one or more stream objects *@paramcloseables List of stream objects that can be closed *@throwsIOException*/     Public Static voidClose (closeable ... closeables)throwsIOException {if(Closeables! =NULL) {             for(closeable closeable:closeables) {if(Closeable! =NULL) {closeable.close (); }            }        }    }    /*** Close one or more Stream objects*/     Public Static voidclosequietly (closeable ... closeables) {Try{Close (closeables); } Catch(IOException e) {// do nothing        }    }}

Java.util.zip Compression and Decompression tool class

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.