Java/File Input Output/GZIP

Материал из Java эксперт
Перейти к: навигация, поиск

A collection of utility methods for working on GZIPed data

 
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
// Commons Logging imports
/**
 *  A collection of utility methods for working on GZIPed data.
 */
public class GZIPUtils {
  
  private static final int EXPECTED_COMPRESSION_RATIO= 5;
  private static final int BUF_SIZE= 4096;
  /**
   * Returns an gunzipped copy of the input array.  If the gzipped
   * input has been truncated or corrupted, a best-effort attempt is
   * made to unzip as much as possible.  If no data can be extracted
   * <code>null</code> is returned.
   */
  public static final byte[] unzipBestEffort(byte[] in) {
    return unzipBestEffort(in, Integer.MAX_VALUE);
  }
  /**
   * Returns an gunzipped copy of the input array, truncated to
   * <code>sizeLimit</code> bytes, if necessary.  If the gzipped input
   * has been truncated or corrupted, a best-effort attempt is made to
   * unzip as much as possible.  If no data can be extracted
   * <code>null</code> is returned.
   */
  public static final byte[] unzipBestEffort(byte[] in, int sizeLimit) {
    try {
      // decompress using GZIPInputStream 
      ByteArrayOutputStream outStream = 
        new ByteArrayOutputStream(EXPECTED_COMPRESSION_RATIO * in.length);
      GZIPInputStream inStream = 
        new GZIPInputStream ( new ByteArrayInputStream(in) );
      byte[] buf = new byte[BUF_SIZE];
      int written = 0;
      while (true) {
        try {
          int size = inStream.read(buf);
          if (size <= 0) 
            break;
          if ((written + size) > sizeLimit) {
            outStream.write(buf, 0, sizeLimit - written);
            break;
          }
          outStream.write(buf, 0, size);
          written+= size;
        } catch (Exception e) {
          break;
        }
      }
      try {
        outStream.close();
      } catch (IOException e) {
      }
      return outStream.toByteArray();
    } catch (IOException e) {
      return null;
    }
  }

  /**
   * Returns an gunzipped copy of the input array.  
   * @throws IOException if the input cannot be properly decompressed
   */
  public static final byte[] unzip(byte[] in) throws IOException {
    // decompress using GZIPInputStream 
    ByteArrayOutputStream outStream = 
      new ByteArrayOutputStream(EXPECTED_COMPRESSION_RATIO * in.length);
    GZIPInputStream inStream = 
      new GZIPInputStream ( new ByteArrayInputStream(in) );
    byte[] buf = new byte[BUF_SIZE];
    while (true) {
      int size = inStream.read(buf);
      if (size <= 0) 
        break;
      outStream.write(buf, 0, size);
    }
    outStream.close();
    return outStream.toByteArray();
  }
  /**
   * Returns an gzipped copy of the input array.
   */
  public static final byte[] zip(byte[] in) {
    try {
      // compress using GZIPOutputStream 
      ByteArrayOutputStream byteOut= 
        new ByteArrayOutputStream(in.length / EXPECTED_COMPRESSION_RATIO);
      GZIPOutputStream outStream= new GZIPOutputStream(byteOut);
      try {
        outStream.write(in);
      } catch (Exception e) {
       
      }
      try {
        outStream.close();
      } catch (IOException e) {
        
      }
      return byteOut.toByteArray();
    } catch (IOException e) {
     
      return null;
    }
  }
    
}





Compress a file in the GZIP format

  
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.GZIPOutputStream;
public class Main {
  public static void main(String[] argv) throws Exception {
    GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream("outfile.gzip"));
    FileInputStream in = new FileInputStream("infilename");
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
      out.write(buf, 0, len);
    }
    in.close();
    out.finish();
    out.close();
  }
}





Compress a list of files passed in from command line

  
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipException;
class ZipDemo {
  private static final int DEFAULT_BUFFER_SIZE = 4096;
  public static final byte[] compress(final String uncompressed) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream zos = new GZIPOutputStream(baos);
    byte[] uncompressedBytes = uncompressed.getBytes();
    zos.write(uncompressedBytes, 0, uncompressedBytes.length);
    zos.close();
    return baos.toByteArray();
  }
  public static final String uncompress(final byte[] compressed) throws IOException {
    String uncompressed = "";
    try {
      ByteArrayInputStream bais = new ByteArrayInputStream(compressed);
      GZIPInputStream zis = new GZIPInputStream(bais);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int numBytesRead = 0;
      byte[] tempBytes = new byte[DEFAULT_BUFFER_SIZE];
      while ((numBytesRead = zis.read(tempBytes, 0, tempBytes.length)) != -1) {
        baos.write(tempBytes, 0, numBytesRead);
      }
      uncompressed = new String(baos.toByteArray());
    } catch (ZipException e) {
      e.printStackTrace(System.err);
    }
    return uncompressed;
  }
  public static final String uncompress(final String compressed) throws IOException {
    return ZipDemo.uncompress(compressed.getBytes());
  }
  public static void main(String[] args) throws Exception{
      for (int i = 0; i < args.length; ++i) {
        String uncompressed = "";
        File f = new File(args[i]);
        if (f.exists()) {
          BufferedReader br = new BufferedReader(new FileReader(f));
          String line = "";
          StringBuffer buffer = new StringBuffer();
          while ((line = br.readLine()) != null)
            buffer.append(line);
          br.close();
          uncompressed = buffer.toString();
        } else {
          uncompressed = args[i];
        }
        byte[] compressed = ZipDemo.rupress(uncompressed);
        String compressedAsString = new String(compressed);
        byte[] bytesFromCompressedAsString = compressedAsString.getBytes();
        bytesFromCompressedAsString.equals(compressed);
        System.out.println(ZipDemo.uncompress(compressed));
        System.out.println(ZipDemo.uncompress(compressedAsString));
     }
  }
}





Compressed socket

  
import java.net.ServerSocket;
import java.net.Socket;
import java.util.zip.GZIPInputStream;
public class Main {
  public static void main(String[] args) throws Exception {
    ServerSocket ssock = new ServerSocket(Integer.parseInt(args[0]));
    Socket sock = ssock.accept();
    GZIPInputStream zip = new GZIPInputStream(sock.getInputStream());
    while (true) {
      int c;
      c = zip.read();
      if (c == -1)
        break;
      System.out.print((char) c);
    }
  }
}





Compressing a File

  
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class CompressIt {
  public static void main(String[] args) {
    String filename = args[0];
    try {
      File file = new File(filename);
      int length = (int) file.length();
      FileInputStream fis = new FileInputStream(file);
      BufferedInputStream bis = new BufferedInputStream(fis);
      ByteArrayOutputStream baos = new ByteArrayOutputStream(length);
      GZIPOutputStream gos = new GZIPOutputStream(baos);
      byte[] buffer = new byte[1024];
      int bytesRead;
      while ((bytesRead = bis.read(buffer)) != -1) {
        gos.write(buffer, 0, bytesRead);
      }
      bis.close();
      gos.close();
      System.out.println("Input Length: " + length);
      System.out.println("Output Length: " + baos.size());
    } catch (FileNotFoundException e) {
      System.err.println("Invalid Filename");
    } catch (IOException e) {
      System.err.println("I/O Exception");
    }
  }
}





Compressing a File in the GZIP Format

  

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.GZIPOutputStream;
public class Main {
  public static void main(String[] argv) throws Exception {
    String outFilename = "outfile.gzip";
    GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outFilename));
    String inFilename = "infilename";
    FileInputStream in = new FileInputStream(inFilename);
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
      out.write(buf, 0, len);
    }
    in.close();
    out.finish();
    out.close();
  }
}





Compress Java objects

  
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.zip.GZIPOutputStream;
public class Main {
  public static void main(String[] args) throws Exception {
    User admin = new User();
    admin.setId(new Long(1));
    User foo = new User();
    foo.setId(new Long(2));
    
    ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(new File("user.dat"))));
    oos.writeObject(admin);
    oos.writeObject(foo);
    oos.flush();
    oos.close();
  }
}
class User implements Serializable {
  private Long id;
  public User() {
  }
  public Long getId() {
    return id;
  }
  public void setId(Long id) {
    this.id = id;
  }
  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("id=").append(id);
    return sb.toString();
  }
}





Decompress Java objects

  
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.zip.GZIPInputStream;
public class Main {
  public static void main(String[] args) throws Exception {
    ObjectInputStream ois = new ObjectInputStream(new GZIPInputStream(new FileInputStream(new File(
        "user.dat"))));
    User admin = (User) ois.readObject();
    User foo = (User) ois.readObject();
    ois.close();
    System.out.println("Admin = [" + admin + "]");
    System.out.println("Foo = [" + foo + "]");
  }
}
class User implements Serializable {
}





GZIP compress

  
// : c12:GZIPcompress.java
// {Args: GZIPcompress.java}
// {Clean: test.gz}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIPcompress {
  // Throw exceptions to console:
  public static void main(String[] args) throws IOException {
    if (args.length == 0) {
      System.out.println("Usage: \nGZIPcompress file\n"
          + "\tUses GZIP compression to compress "
          + "the file to test.gz");
      System.exit(1);
    }
    BufferedReader in = new BufferedReader(new FileReader(args[0]));
    BufferedOutputStream out = new BufferedOutputStream(
        new GZIPOutputStream(new FileOutputStream("test.gz")));
    System.out.println("Writing file");
    int c;
    while ((c = in.read()) != -1)
      out.write(c);
    in.close();
    out.close();
    System.out.println("Reading file");
    BufferedReader in2 = new BufferedReader(new InputStreamReader(
        new GZIPInputStream(new FileInputStream("test.gz"))));
    String s;
    while ((s = in2.readLine()) != null)
      System.out.println(s);
  }
} ///:~





GZIP Filter, response stream and Response Wrapper

 
/*
 * Copyright 2003 Jayson Falkner (jayson@jspinsider.ru)
 * This code is from "Servlets and JavaServer pages; the J2EE Web Tier",
 * http://www.jspbook.ru. You may freely use the code both commercially
 * and non-commercially. If you like the code, please pick up a copy of
 * the book and help support the authors, development of more free code,
 * and the JSP/Servlet/J2EE community.
 */
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.zip.GZIPOutputStream;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
public class GZIPFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res,
      FilterChain chain) throws IOException, ServletException {
    if (req instanceof HttpServletRequest) {
      HttpServletRequest request = (HttpServletRequest) req;
      HttpServletResponse response = (HttpServletResponse) res;
      String ae = request.getHeader("accept-encoding");
      if (ae != null && ae.indexOf("gzip") != -1) {        
        GZIPResponseWrapper wrappedResponse = new GZIPResponseWrapper(response);
        chain.doFilter(req, wrappedResponse);
        wrappedResponse.finishResponse();
        return;
      }
      chain.doFilter(req, res);
    }
  }
  public void init(FilterConfig filterConfig) {
    // noop
  }
  public void destroy() {
    // noop
  }
}
/*
 * Copyright 2003 Jayson Falkner (jayson@jspinsider.ru)
 * This code is from "Servlets and JavaServer pages; the J2EE Web Tier",
 * http://www.jspbook.ru. You may freely use the code both commercially
 * and non-commercially. If you like the code, please pick up a copy of
 * the book and help support the authors, development of more free code,
 * and the JSP/Servlet/J2EE community.
 */
class GZIPResponseStream extends ServletOutputStream { 
  protected ByteArrayOutputStream baos = null;
  protected GZIPOutputStream gzipstream = null;
  protected boolean closed = false;
  protected HttpServletResponse response = null;
  protected ServletOutputStream output = null;
  public GZIPResponseStream(HttpServletResponse response) throws IOException {
    super();
    closed = false;
    this.response = response;
    this.output = response.getOutputStream();
    baos = new ByteArrayOutputStream();
    gzipstream = new GZIPOutputStream(baos);
  }
  public void close() throws IOException {
    if (closed) {
      throw new IOException("This output stream has already been closed");
    }
    gzipstream.finish();
    byte[] bytes = baos.toByteArray();

    response.addHeader("Content-Length", 
                       Integer.toString(bytes.length)); 
    response.addHeader("Content-Encoding", "gzip");
    output.write(bytes);
    output.flush();
    output.close();
    closed = true;
  }
  public void flush() throws IOException {
    if (closed) {
      throw new IOException("Cannot flush a closed output stream");
    }
    gzipstream.flush();
  }
  public void write(int b) throws IOException {
    if (closed) {
      throw new IOException("Cannot write to a closed output stream");
    }
    gzipstream.write((byte)b);
  }
  public void write(byte b[]) throws IOException {
    write(b, 0, b.length);
  }
  public void write(byte b[], int off, int len) throws IOException {
    if (closed) {
      throw new IOException("Cannot write to a closed output stream");
    }
    gzipstream.write(b, off, len);
  }
  public boolean closed() {
    return (this.closed);
  }
  
  public void reset() {
    //noop
  }
}
/*
 * Copyright 2003 Jayson Falkner (jayson@jspinsider.ru)
 * This code is from "Servlets and JavaServer pages; the J2EE Web Tier",
 * http://www.jspbook.ru. You may freely use the code both commercially
 * and non-commercially. If you like the code, please pick up a copy of
 * the book and help support the authors, development of more free code,
 * and the JSP/Servlet/J2EE community.
 */
 class GZIPResponseWrapper extends HttpServletResponseWrapper {
  protected HttpServletResponse origResponse = null;
  protected ServletOutputStream stream = null;
  protected PrintWriter writer = null;
  public GZIPResponseWrapper(HttpServletResponse response) {
    super(response);
    origResponse = response;
  }
  public ServletOutputStream createOutputStream() throws IOException {
    return (new GZIPResponseStream(origResponse));
  }
  public void finishResponse() {
    try {
      if (writer != null) {
        writer.close();
      } else {
        if (stream != null) {
          stream.close();
        }
      }
    } catch (IOException e) {}
  }
  public void flushBuffer() throws IOException {
    stream.flush();
  }
  public ServletOutputStream getOutputStream() throws IOException {
    if (writer != null) {
      throw new IllegalStateException("getWriter() has already been called!");
    }
    if (stream == null)
      stream = createOutputStream();
    return (stream);
  }
  public PrintWriter getWriter() throws IOException {
    if (writer != null) {
      return (writer);
    }
    if (stream != null) {
      throw new IllegalStateException("getOutputStream() has already been called!");
    }
   stream = createOutputStream();
   writer = new PrintWriter(new OutputStreamWriter(stream, "UTF-8"));
   return (writer);
  }
  public void setContentLength(int length) {}
}





gzipping files and zipping directories

  
 
/*
 * Copyright (c) 2004 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 3nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose,
 * including teaching and use in open-source projects.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book, 
 * please visit http://www.davidflanagan.ru/javaexamples3.
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
 * This class defines two static methods for gzipping files and zipping
 * directories. It also defines a demonstration program as a nested class.
 */
public class Compress {
  /** Gzip the contents of the from file and save in the to file. */
  public static void gzipFile(String from, String to) throws IOException {
    // Create stream to read from the from file
    FileInputStream in = new FileInputStream(from);
    // Create stream to compress data and write it to the to file.
    GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(to));
    // Copy bytes from one stream to the other
    byte[] buffer = new byte[4096];
    int bytes_read;
    while ((bytes_read = in.read(buffer)) != -1)
      out.write(buffer, 0, bytes_read);
    // And close the streams
    in.close();
    out.close();
  }
  /** Zip the contents of the directory, and save it in the zipfile */
  public static void zipDirectory(String dir, String zipfile) throws IOException,
      IllegalArgumentException {
    // Check that the directory is a directory, and get its contents
    File d = new File(dir);
    if (!d.isDirectory())
      throw new IllegalArgumentException("Compress: not a directory:  " + dir);
    String[] entries = d.list();
    byte[] buffer = new byte[4096]; // Create a buffer for copying
    int bytes_read;
    // Create a stream to compress data and write it to the zipfile
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
    // Loop through all entries in the directory
    for (int i = 0; i < entries.length; i++) {
      File f = new File(d, entries[i]);
      if (f.isDirectory())
        continue; // Don"t zip sub-directories
      FileInputStream in = new FileInputStream(f); // Stream to read file
      ZipEntry entry = new ZipEntry(f.getPath()); // Make a ZipEntry
      out.putNextEntry(entry); // Store entry
      while ((bytes_read = in.read(buffer)) != -1)
        // Copy bytes
        out.write(buffer, 0, bytes_read);
      in.close(); // Close input stream
    }
    // When we"re done with the whole loop, close the output stream
    out.close();
  }
  /**
   * This nested class is a test program that demonstrates the use of the static
   * methods defined above.
   */
  public static class Test {
    /**
     * Compress a specified file or directory. If no destination name is
     * specified, append .gz to a file name or .zip to a directory name
     */
    public static void main(String args[]) throws IOException {
      if ((args.length != 1) && (args.length != 2)) { // check arguments
        System.err.println("Usage: java Compress$Test <from> [<to>]");
        System.exit(0);
      }
      String from = args[0], to;
      File f = new File(from);
      boolean directory = f.isDirectory(); // Is it a file or directory?
      if (args.length == 2)
        to = args[1];
      else { // If destination not specified
        if (directory)
          to = from + ".zip"; // use a .zip suffix
        else
          to = from + ".gz"; // or a .gz suffix
      }
      if ((new File(to)).exists()) { // Make sure not to overwrite
        System.err.println("Compress: won"t overwrite existing file: " + to);
        System.exit(0);
      }
      // Finally, call one of the methods defined above to do the work.
      if (directory)
        Compress.zipDirectory(from, to);
      else
        Compress.gzipFile(from, to);
    }
  }
}





GZip with GZIPOutputStream

  
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
public class Main {
  public static void main(String[] args) throws Exception {
    InputStream fin = new FileInputStream("a.dat");
    OutputStream fout = new FileOutputStream("a.dat.gz");
    GZIPOutputStream gzout = new GZIPOutputStream(fout);
    for (int c = fin.read(); c != -1; c = fin.read()) {
      gzout.write(c);
    }
    gzout.close();
  }
}





Reads GZIP, Zip, and Jar files

 
/*
 * Copyright (C) 2005 Caio Filipini, Sergio Umlauf
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Created on 14/09/2005
 *
 */
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
 * Reads GZIP, Zip, and Jar files
 *
 * @author Sergio Umlauf
 *
 */
public class Zip {
   /**
    * Reads a GZIP file and dumps the contents to the console.
    */
  public static void readGZIPFile(String fileName) {
      // use BufferedReader to get one line at a time
      BufferedReader gzipReader = null;
      try {
         // simple loop to dump the contents to the console
         gzipReader = new BufferedReader(
               new InputStreamReader(
                new GZIPInputStream(
                new FileInputStream(fileName))));
         while (gzipReader.ready()) {
            System.out.println(gzipReader.readLine());
         }
         gzipReader.close();
     } catch (FileNotFoundException fnfe) {
         System.out.println("The file was not found: " + fnfe.getMessage());
      } catch (IOException ioe) {
         System.out.println("An IOException occurred: " + ioe.getMessage());
      } finally {
         if (gzipReader != null) {
            try { gzipReader.close(); } catch (IOException ioe) {}
         }
      }
   }
   /**
    * Reads a Zip file, iterating through each entry and dumping the contents
    * to the console.
    */
  public static void readZipFile(String fileName) {
      ZipFile zipFile = null;
      try {
         // ZipFile offers an Enumeration of all the files in the Zip file
         zipFile = new ZipFile(fileName);
         for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
            ZipEntry zipEntry = (ZipEntry) e.nextElement();
            System.out.println(zipEntry.getName() + " contains:");
            // use BufferedReader to get one line at a time
            BufferedReader zipReader = new BufferedReader(
                 new InputStreamReader(zipFile.getInputStream(zipEntry)));
            while (zipReader.ready()) {
               System.out.println(zipReader.readLine());
            }
            zipReader.close();
         }
      } catch (IOException ioe) {
         System.out.println("An IOException occurred: " + ioe.getMessage());
      } finally {
         if (zipFile != null) {
            try { zipFile.close(); } catch (IOException ioe) {}
         }
      }
   }
   /**
    * Reads a Jar file, displaying the attributes in its manifest and dumping
    * the contents of each file contained to the console.
    */
  public static void readJarFile(String fileName) {
      JarFile jarFile = null;
      try {
         // JarFile extends ZipFile and adds manifest information
         jarFile = new JarFile(fileName);
         if (jarFile.getManifest() != null) {
            System.out.println("Manifest Main Attributes:");
            Iterator iter =
              jarFile.getManifest().getMainAttributes().keySet().iterator();
            while (iter.hasNext()) {
               Attributes.Name attribute = (Attributes.Name) iter.next();
               System.out.println(attribute + " : " +
                   jarFile.getManifest().getMainAttributes().getValue(attribute));
            }
            System.out.println();
         }
         // use the Enumeration to dump the contents of each file to the console
         System.out.println("Jar file entries:");
         for (Enumeration e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) e.nextElement();
            if (!jarEntry.isDirectory()) {
               System.out.println(jarEntry.getName() + " contains:");
               BufferedReader jarReader = new BufferedReader(
                  new InputStreamReader(jarFile.getInputStream(jarEntry)));
               while (jarReader.ready()) {
                  System.out.println(jarReader.readLine());
               }
               jarReader.close();
            }
         }
      } catch (IOException ioe) {
         System.out.println("An IOException occurred: " + ioe.getMessage());
      } finally {
         if (jarFile != null) {
            try { jarFile.close(); } catch (IOException ioe) {}
         }
      }
   }
}





Read some data from a gzip file

  
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
/**
 * Read some data from a gzip file.
 * 
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: ReadGZIP.java,v 1.4 2004/03/06 20:54:38 ian Exp $
 */
public class ReadGZIP {
  public static void main(String[] argv) throws IOException {
    String FILENAME = "file.txt.gz";
    // Since there are 4 constructor calls here, I wrote them out in full.
    // In real life you would probably nest these constructor calls.
    FileInputStream fin = new FileInputStream(FILENAME);
    GZIPInputStream gzis = new GZIPInputStream(fin);
    InputStreamReader xover = new InputStreamReader(gzis);
    BufferedReader is = new BufferedReader(xover);
    String line;
    // Now read lines of text: the BufferedReader puts them in lines,
    // the InputStreamReader does Unicode conversion, and the
    // GZipInputStream "gunzip"s the data from the FileInputStream.
    while ((line = is.readLine()) != null)
      System.out.println("Read: " + line);
  }
}





Uncompress a file in the GZIP format

  
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
public class Main {
  public static void main(String[] argv) throws Exception {
    String source = "s.gzip";
    GZIPInputStream in = new GZIPInputStream(new FileInputStream(source));
    String target = "outfile";
    OutputStream out = new FileOutputStream(target);
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
      out.write(buf, 0, len);
    }
    in.close();
    out.close();
  }
}





Uncompressing a File in the GZIP Format

  
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
public class Main {
  public static void main(String[] argv) throws Exception {
    String inFilename = "infile.gzip";
    GZIPInputStream in = new GZIPInputStream(new FileInputStream(inFilename));
    String outFilename = "outfile";
    OutputStream out = new FileOutputStream(outFilename);
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
      out.write(buf, 0, len);
    }
    in.close();
    out.close();
  }
}





Ungzip with GZIPInputStream

  
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.GZIPInputStream;
public class Main {
  public static void main(String[] args) throws Exception {
    FileInputStream fin = new FileInputStream("a.gz");
    GZIPInputStream gzin = new GZIPInputStream(fin);
    FileOutputStream fout = new FileOutputStream("a.dat");
    for (int c = gzin.read(); c != -1; c = gzin.read()) {
      fout.write(c);
    }
    fout.close();
  }
}