`
george.gu
  • 浏览: 71306 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Manage zip content using Java APIs

阅读更多

JDK provide a set of utils to compress and decompress data by zip format. You can find technical guide from http://java.sun.com/developer/technicalArticles/Programming/compression/.

 

Here is my sumarrize during study how to use java zip utils. You can find those APIs from java.util.zip.*.

ZipEntry:

Represents a ZIP file entry inside ZIP content. It could be a file or a directory. 

 

Method Signature Description
public boolean isDirectory() Returns true if this is a directory entry.
public long getCompressedSize() Returns the compressed size of the entry, -1 if not known
public int getMethod() Returns the compression method of the entry, -1 if not specified
public String getName() Returns the name of the entry
public long getSize() Returns the uncompressed zip of the entry, -1 if unknown
public long getTime() Returns the modification time of the entry, -1 if not specified
public void setComment(String c) Sets the optional comment string for the entry
public void setMethod(int method) Sets the compression method for the entry
public void setSize(long size) Sets the uncompressed size of the entry
public void setTime(long time) Sets the modification time of the entry

 

 

 

ZipInputStream: Decompressing and Extract data from a ZIP file

 

ZipInputStream is used to decompress and extract data from Zip file.

A ZipInputStream can be created just like any other input stream. For example, the following segment of code can be used to create an input stream for reading data from a ZIP file format:

 

FileInputStream fis = new FileInputStream("figs.zip");

ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis));

 

Once a ZIP input stream is opened, you can read the zip entries using the getNextEntry method which returns a ZipEntry object. If the end-of-file is reached, getNextEntry returns null:

 

ZipEntry entry;

while((entry = zin.getNextEntry()) != null) {

   // extract data

   // open output streams

}

 

 

 

ZipOutputStream: Compressing and Archiving Data in a ZIP File

The ZipOutputStream can be used to compress data to a ZIP file. The ZipOutputStream writes data to an output stream in a ZIP format.

 

If you output a entry like "path1/path2/filename.xml", ZipOutputStream will automatically create two additional directory entry "path1/" and "path1/path2/".

 

Here is a utility method to compress data into dedicated entry:

 

    /**

     * Add a Zip entry with a specified name to an output stream

     * and write the bytes using the compression method

     * @param entryName name of Zip entry

     * @param zipos a Zip output stream

     * @param bytes byte array corresponding to new Zip entry

     * @throws IOException if output stream cannot be written

     */

    public static void doZip(String entryName, ZipOutputStream zipos, byte[] bytes) throws IOException {

        ZipEntry ze = new ZipEntry(entryName);

        int size = bytes.length;

        ze.setSize(size);

 

        zipos.putNextEntry(ze);

        zipos.write(bytes, 0, size);

        zipos.closeEntry();

    }

 

ZipFile:

ZipFile is used to read entries from a ZIP file. You can use ZipFile to decompress Zip file. It is like a wrapper to ZipInputStream.

import java.io.*;

import java.util.*;

import java.util.zip.*;


public class UnZip2 {

   static final int BUFFER = 2048;

   public static void main (String args[]) {

      try {

         BufferedOutputStream dest = null;

         BufferedInputStream is = null;

         ZipEntry entry;

         ZipFile zipfile = new ZipFile("myfile.zip");

         Enumeration e = zipfile.entries();

         while(e.hasMoreElements()) {

            entry = (ZipEntry) e.nextElement();

            System.out.println("Extracting: " +entry);

            is = new BufferedInputStream(zipfile.getInputStream(entry));

            int count;

            byte data[] = new byte[BUFFER];

            FileOutputStream fos = new FileOutputStream(entry.getName());

            dest = new BufferedOutputStream(fos, BUFFER);

            while ((count = is.read(data, 0, BUFFER))!= -1) {

               dest.write(data, 0, count);

            }

            dest.flush();

            dest.close();

            is.close();

         }

      } catch(Exception e) {

         e.printStackTrace();

      }

   }

}

Please Note:

  1. The ZipInputStream class reads ZIP files sequentially. However class ZipFile reads the contents of a ZIP file using a random access file internally so that the entries of the ZIP file do not have to be read sequentially.
  2. Zip entries are not cached when the file is read using a combination of ZipInputStream and FileInputStream. However, if the file is opened using ZipFile(fileName) then it is cached internally, so if ZipFile(fileName) is called again the file is opened only once. The cached value is used on the second open. 

Compressing Object

You can also use Zip utils to compress and decompress java object. Let's talk about that later.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics