UnZip -- print or unzip a JAR or PKZIP file using java.util.zip : Zip Tar File « File Input Output « Java






UnZip -- print or unzip a JAR or PKZIP file using java.util.zip

         

/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 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.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * UnZip -- print or unzip a JAR or PKZIP file using java.util.zip. Command-line
 * version: extracts files.
 * 
 * @author Ian Darwin, Ian@DarwinSys.com $Id: UnZip.java,v 1.7 2004/03/07
 *         17:40:35 ian Exp $
 */
public class UnZip {
  /** Constants for mode listing or mode extracting. */
  public static final int LIST = 0, EXTRACT = 1;

  /** Whether we are extracting or just printing TOC */
  protected int mode = LIST;

  /** The ZipFile that is used to read an archive */
  protected ZipFile zippy;

  /** The buffer for reading/writing the ZipFile data */
  protected byte[] b;

  /**
   * Simple main program, construct an UnZipper, process each .ZIP file from
   * argv[] through that object.
   */
  public static void main(String[] argv) {
    UnZip u = new UnZip();

    for (int i = 0; i < argv.length; i++) {
      if ("-x".equals(argv[i])) {
        u.setMode(EXTRACT);
        continue;
      }
      String candidate = argv[i];
      // System.err.println("Trying path " + candidate);
      if (candidate.endsWith(".zip") || candidate.endsWith(".jar"))
        u.unZip(candidate);
      else
        System.err.println("Not a zip file? " + candidate);
    }
    System.err.println("All done!");
  }

  /** Construct an UnZip object. Just allocate the buffer */
  UnZip() {
    b = new byte[8092];
  }

  /** Set the Mode (list, extract). */
  protected void setMode(int m) {
    if (m == LIST || m == EXTRACT)
      mode = m;
  }

  /** Cache of paths we've mkdir()ed. */
  protected SortedSet dirsMade;

  /** For a given Zip file, process each entry. */
  public void unZip(String fileName) {
    dirsMade = new TreeSet();
    try {
      zippy = new ZipFile(fileName);
      Enumeration all = zippy.entries();
      while (all.hasMoreElements()) {
        getFile((ZipEntry) all.nextElement());
      }
    } catch (IOException err) {
      System.err.println("IO Error: " + err);
      return;
    }
  }

  protected boolean warnedMkDir = false;

  /**
   * Process one file from the zip, given its name. Either print the name, or
   * create the file on disk.
   */
  protected void getFile(ZipEntry e) throws IOException {
    String zipName = e.getName();
    switch (mode) {
    case EXTRACT:
      if (zipName.startsWith("/")) {
        if (!warnedMkDir)
          System.out.println("Ignoring absolute paths");
        warnedMkDir = true;
        zipName = zipName.substring(1);
      }
      // if a directory, just return. We mkdir for every file,
      // since some widely-used Zip creators don't put out
      // any directory entries, or put them in the wrong place.
      if (zipName.endsWith("/")) {
        return;
      }
      // Else must be a file; open the file for output
      // Get the directory part.
      int ix = zipName.lastIndexOf('/');
      if (ix > 0) {
        String dirName = zipName.substring(0, ix);
        if (!dirsMade.contains(dirName)) {
          File d = new File(dirName);
          // If it already exists as a dir, don't do anything
          if (!(d.exists() && d.isDirectory())) {
            // Try to create the directory, warn if it fails
            System.out.println("Creating Directory: " + dirName);
            if (!d.mkdirs()) {
              System.err.println("Warning: unable to mkdir "
                  + dirName);
            }
            dirsMade.add(dirName);
          }
        }
      }
      System.err.println("Creating " + zipName);
      FileOutputStream os = new FileOutputStream(zipName);
      InputStream is = zippy.getInputStream(e);
      int n = 0;
      while ((n = is.read(b)) > 0)
        os.write(b, 0, n);
      is.close();
      os.close();
      break;
    case LIST:
      // Not extracting, just list
      if (e.isDirectory()) {
        System.out.println("Directory " + zipName);
      } else {
        System.out.println("File " + zipName);
      }
      break;
    default:
      throw new IllegalStateException("mode value (" + mode + ") bad");
    }
  }
}

           
         
    
    
    
    
    
    
    
    
  








Related examples in the same category

1.Extract contents of a zip file
2.List the contents of a zip file
3.Read entries in a zip / compressed file
4.Decompress a zip file using ZipInputStream
5.Decompress a zip file using ZipFile
6.Create checksum for a zip file
7.Read a zip file checksum value
8.Create a zip file with java.util.zip package
9.Extract file/files from a zip file
10.Read files within a zip file
11.Retrieve a compressed file from a ZIP file
12.Retrieve the contents of a ZIP file
13.Making a zip file of directory including its subdirectories recursively
14.Displaying contents of a compressed zip file
15.Compress a Byte Array
16.Decompress a Byte Array
17.Read zip file
18.Write Zip file
19.The java.util.zip package can be used to create a checksum.
20.Read the content of a zip file ZipFile
21.List the entries of a zip file
22.Compressing Streams: Zipper, Java example
23.Compressing Streams: Parity Checksum
24.Compressing Streams: File Summer
25.Create a simple ZIP File: not retain any directory path information about the files.
26.Decompress a ZIP file.
27.Decompressing a Byte Array
28.Zip unzip byte array
29.Creating a ZIP File
30.Listing the Contents of a ZIP File
31.Retrieving a Compressed File from a ZIP File
32.Calculating the Checksum of a Byte Array (Compute Adler-32 checksum)
33.Compute CRC-32 checksum
34.Calculating the Checksum of a File
35.Compress string(byte array) by Deflater
36.Use Java code to zip a folder
37.Uses Zip compression to compress any number of files given on the command line
38.Load zip file and scan zip file
39.Reading the Contents of a ZIP File
40.Tape Archive Lister: Tar file
41.Compressing a Byte Array
42.Tar file stream
43.Tar file and untar file
44.bzip source code
45.Unpack an archive from a URL
46.Compare two zip files
47.Determine whether a file is a ZIP File.
48.Zip up a directory
49.Check sum for a path
50.Check sum for an InputStream
51.Extract zip file to destination folder
52.Return the first directory of this archive. This is needed to determine the plugin directory
53.Makes a zip file named xmlFileName from xmlURL at path
54.Unzipps a zip file placed at zipURL to path
55.A single checksum calculation for multiple files
56.Put file To Zip File
57.Provides both writing and reading from a file which is transparently compressed in Zip
58.TarInputStream reads a UNIX tar archive as an InputStream
59.TarOutputStream writes a UNIX tar archive as an OutputStream
60.Package files utility
61.Zip Compare
62.Unpack a segment from a zip
63.Unpack a zip file
64.Unzip file to a directory
65.Zip a list of file into one zip file.
66.Validate that an archive contains a named entry
67.A frame with a text area to show the contents of a file inside a ZIP archive
68.Compress object and decompress
69.Util for extracting *.jar, *.war and *.zip archives.