`
george.gu
  • 浏览: 73538 次
  • 性别: 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.

分享到:
评论

相关推荐

    IBM FileNet P8 v4.5 Content Engine Development Java API chm

    IBM FileNet P8 v4.5 Content Engine Development Java API 打包成chm格式,看起来方便

    Bluetooth Application Programming with the Java APIs Essentials Edition

    《Bluetooth Application Programming with the Java APIs Essentials Edition》是一本专门介绍如何使用Java技术进行蓝牙应用开发的专业书籍。该书由Morgan Kaufmann出版社出版,首次发布于2008年2月。本书的主要...

    Gearman java APIs和一个小Demo

    在提供的 `Gearman_java_Demo.zip` 文件中,你应该能找到一个简单的 Gearman Java 示例。这个示例包括了客户端和工作者两部分,客户端提交一个字符串反转的任务,工作者接收到任务后进行反转并返回结果。 运行这个 ...

    Building Trading Bots Using Java [2016]

    In this book, you will learn about the nitty-gritty of automated trading and have a closer look at Java, the Spring Framework, event-driven programming, and other open source APIs, notably Google's ...

    xml-apis.zip_JAVA XML_java xml_xml_zip

    "xml-apis.zip" 是一个包含Java XML API的压缩包,它提供了处理XML所需的基本接口和类。 "xml-apis.zip" 中的"xml-apis.jar" 文件是XML API的核心库,包含了多个与XML处理相关的Java包,如javax.xml、org.w3c.dom和...

    Java™ Media APIs(chm)

    Java™ Media APIs是Java开发平台中的一个重要组成部分,它为开发者提供了处理多媒体数据的强大工具。这个chm文件,"Sams.Java.Media.APIs.eBook-LiB.chm",很可能是关于Java媒体APIs的详细指南或参考文档,包含了...

    Java APIs, Extensions and Libraries-Apress(2018).pdf

    Java APIs, Extensions and Libraries_With JavaFX, JDBC, jmod, jlink, Networking, and the Process API-Apress(2018).pdf I am pleased to present the second edition of the Java APIs, Extensions, and ...

    java_ee_sdk-8u1.zip

    This release modernizes support for many industry standards and continues simplification of enterprise ready APIs. Enhancements include: Java Servlet 4.0 API with HTTP/2 support Enhanced JSON ...

    Bluetooth Application Programming with the Java APIs

    《蓝牙应用编程与Java API》一书是针对蓝牙技术与Java编程结合的深入研究与实践指南,由CBalaKumar、PaulJ.Kline和TimothyJ.Thompson共同编写,属于TheMorganKaufmannSeriesinNetworking系列,该系列由MIT的大卫·...

    Morgan Kaufmann - Bluetooth Application Programming with the Java APIs (Feb 2008)

    《使用Java APIs进行蓝牙应用程序编程》是一本专为IT专业人士准备的指南,旨在深入探讨如何利用Java技术开发蓝牙应用。本书由Morgan Kaufmann出版社在2008年出版,聚焦于蓝牙通信协议栈与Java API的结合,帮助开发者...

    Api-apis.zip

    Api-apis.zip,让任何感兴趣的人都可以随时获得数据。这是自2012年以来让数据变得漂亮!,一个api可以被认为是多个软件设备之间通信的指导手册。例如,api可用于web应用程序之间的数据库通信。通过提取实现并将数据...

    Java APIs, Extensions and Libraries, 2nd Edition--2018

    Connect to databases and access data from Java programs using the JDBC API Work with JavaFX, RMI (Remote Method Invocation), and JNI (Java Native Interface) Use the new scripting features of Java

    Java APIs, Extensions and Libraries With JavaFX, JDBC, jmod, API(2nd) epub

    Java APIs, Extensions and Libraries With JavaFX, JDBC, jmod, jlink, Networking, and the Process API(2nd) 英文epub 第2版 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国...

    Java APIs, Extensions and Libraries With JavaFX, JDBC, jmod, API(2nd) 无水印原版pdf

    Java APIs, Extensions and Libraries With JavaFX, JDBC, jmod, jlink, Networking, and the Process API(2nd) 英文无水印原版pdf 第2版 pdf所有页面使用FoxitReader、PDF-XChangeViewer、SumatraPDF和Firefox...

    ios-iOS 9 学习系列: Search-APIs.zip

    在 iOS9 之前,你只能在 spotlight 中输入...在 iOS9 中苹果提供了一套 Search APIs。允许开发者选择应用的内容,索引起来供 spotlight 进行搜索,同时可以设置在 spotlight 中的展示效果,以及点击之后如何响应。

    Pro JPA 2 in Java EE 8: An In-Depth Guide to Java Persistence APIs.pdf

    After completing Pro JPA 2 in Java EE 8, you will have a full understanding of JPA and be able to successfully code applications using its annotations and APIs. The book also serves as an excellent ...

    xml-apis-1.4.01.jar.zip

    `xml-apis-1.4.01.jar` 是一个包含XML API实现的Java库,它提供了处理XML文档所需的基本接口和类。在Java开发中,如果遇到“xml-apis-1.4.01.jar does not exist”的错误,通常意味着项目缺少了对XML解析的支持。 ...

    Java(TM) EE 8 Specification APIs(Java(TM) EE 8规范API)

    Java(TM) EE 8 Specification APIs,即Java(TM) EE 8规范API。本CHM文档是根据由javadoc(1.8.0_144)于2017年9月生成的HTML文档制作而成的,原版英文文档。

Global site tag (gtag.js) - Google Analytics