Zip unzip byte array : Zip Tar File « File Input Output « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JDK 6
25.JNDI LDAP
26.JPA
27.JSP
28.JSTL
29.Language Basics
30.Network Protocol
31.PDF RTF
32.Reflection
33.Regular Expressions
34.Scripting
35.Security
36.Servlets
37.Spring
38.Swing Components
39.Swing JFC
40.SWT JFace Eclipse
41.Threads
42.Tiny Application
43.Velocity
44.Web Services SOA
45.XML
Java » File Input Output » Zip Tar FileScreenshots 
Zip unzip byte array
       
/*
 *  Copyright (C) 2001, 2002 Robert MacGrogan
 *
 *  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
 *
 *
 * $Archive: SourceJammer$
 * $FileName: ZipUtil.java$
 * $FileID: 4327$
 *
 * Last change:
 * $AuthorName: Rob MacGrogan$
 * $Date: 4/23/03 5:23 PM$
 * $Comment: Replaced GPL header with LGPL header.$
 *
 * $KeyWordsOff: $
 */


/**
 * Title:        SourceJammer Library 1.0
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:      SourceJammer Project
 @author Robert MacGrogan
 @version 1.0
 */

import java.util.HashMap;
import java.util.zip.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.*;

/**
 * Static utility methods for zipping data.
 */
public class ZipUtil {

  public static final int ZIP_BUFFER_SIZE = 50;
  private static final int STREAM_BUFFER_SIZE = 1024;

  private ZipUtil() {
  }

  /**
   * Deflates the file and returns the deflated file.
   */
  public static byte[] zipByteArray(byte[] file)
          throws IOException{
    byte[] byReturn = null;
    Deflater oDeflate = new Deflater(Deflater.DEFLATED, false);
    oDeflate.setInput(file);
    oDeflate.finish();
    ByteArrayOutputStream oZipStream = new ByteArrayOutputStream();
    try {
      while (! oDeflate.finished() ){
        byte[] byRead = new byte[ZIP_BUFFER_SIZE];
        int iBytesRead = oDeflate.deflate(byRead);
        if (iBytesRead == byRead.length){
          oZipStream.write(byRead);
        }
        else {
          oZipStream.write(byRead, 0, iBytesRead);
        }
      }
      oDeflate.end();
      byReturn = oZipStream.toByteArray();
    }
    finally {
      oZipStream.close();
    }
    return byReturn;
  }

  /**
   * Inflates a previously deflated file.
   */
  public static byte[] unzipByteArray(byte[] file)
          throws IOException {
    byte[] byReturn = null;

    Inflater oInflate = new Inflater(false);
    oInflate.setInput(file);

    ByteArrayOutputStream oZipStream = new ByteArrayOutputStream();
    try {
      while (! oInflate.finished() ){
        byte[] byRead = new byte[ZIP_BUFFER_SIZE];
        int iBytesRead = oInflate.inflate(byRead);
        if (iBytesRead == byRead.length){
          oZipStream.write(byRead);
        }
        else {
          oZipStream.write(byRead, 0, iBytesRead);
        }
      }
      byReturn = oZipStream.toByteArray();
    }
    catch (DataFormatException ex){
      throw new IOException("Attempting to unzip file that is not zipped.");
    }
    finally {
      oZipStream.close();
    }
    return byReturn;
  }

/*
  public static void zipFileToFile(File flSource, File flTarget)
          throws IOException{
    Deflater oDeflate = new Deflater(Deflater.DEFLATED, false);

    FileInputStream stmFileIn = new FileInputStream(flSource);
    FileOutputStream stmFileOut = new FileOutputStream(flTarget);
    DeflaterOutputStream stmDeflateOut = new DeflaterOutputStream(stmFileOut, oDeflate);
    byte[] buffer = null;
    int iBufferSize = STREAM_BUFFER_SIZE;

    boolean bKeepZipping = true;
    try{
      while (bKeepZipping){
        buffer = new byte[iBufferSize];
        int iBytes = stmFileIn.read(buffer);
        if (iBytes == -1){
          bKeepZipping = false;
        }
        else{
          if (iBytes < iBufferSize){
            bKeepZipping = false;
            byte[] tmp = new byte[iBytes];
            for (int i = 0; i < iBytes; i++){
              tmp[i] = buffer[i];
            }
            buffer = tmp;
          }
          stmDeflateOut.write(buffer);
        }//end else some bytes returned.
      }//end while
    }//end try
    finally{
      stmDeflateOut.finish();
      stmDeflateOut.flush();
      stmDeflateOut.close();
      stmFileOut.close();
      stmFileIn.close();
    }
  }
*/


  public static void zipFileToFile(File flSource, File flTarget)
          throws IOException{
    Deflater oDeflate = new Deflater(Deflater.DEFLATED, false);

    FileInputStream stmFileIn = new FileInputStream(flSource);
    FileOutputStream stmFileOut = new FileOutputStream(flTarget);
    DeflaterOutputStream stmDeflateOut = new DeflaterOutputStream(stmFileOut, oDeflate);
    try{
     // FileUtil.inputStreamToOutputStream(stmFileIn, stmDeflateOut);
    }//end try
    finally{
      stmDeflateOut.finish();
      stmDeflateOut.flush();
      stmDeflateOut.close();
      stmFileOut.close();
      stmFileIn.close();
    }
  }


  public static void unzipFileToFile(File flSource, File flTarget)
          throws IOException{
    Inflater oInflate = new Inflater(false);
    FileInputStream stmFileIn = new FileInputStream(flSource);
    FileOutputStream stmFileOut = new FileOutputStream(flTarget);
    InflaterInputStream stmInflateIn = new InflaterInputStream(stmFileIn, oInflate);

    try{
      inflaterInputStmToFileOutputStm(stmInflateIn, stmFileOut);
    }//end try
    finally{
      stmFileOut.flush();
      stmFileOut.close();
      stmInflateIn.close();
      stmFileIn.close();
    }
  }

  private static void inflaterInputStmToFileOutputStm(InflaterInputStream stmIn,
                                              FileOutputStream stmOut)
          throws IOException{
    byte[] buffer = null;
    int iBufferSize = STREAM_BUFFER_SIZE;

    boolean bKeepStreaming = true;
    while (bKeepStreaming){
      buffer = new byte[iBufferSize];
      int iBytes = stmIn.read(buffer);
      if (iBytes == -1){
        bKeepStreaming = false;
      }
      else{
        if (iBytes < iBufferSize){
          bKeepStreaming = false;
          byte[] tmp = new byte[iBytes];
          for (int i = 0; i < iBytes; i++){
            tmp[i= buffer[i];
          }
          buffer = tmp;
        }
        stmOut.write(buffer);
        //Override above test if available returns 1
        if (stmIn.available() == 1){
          bKeepStreaming = true;
        }
      }//end else some bytes returned.
    }//end while
  }

  /**
   * Checks passed-in file name against list of extensions not to zip. Returns
   * true if no matches, false if a match to file extension is found.
   */
  public static boolean canZip(String fileName){
    boolean bCanZip = true;
    return bCanZip;
  }

  public static void main(String[] args){
    try {
      File flSource = new File(args[0]);
      File flTarget = new File(args[1]);
      System.out.println("Unzipping file");

      unZipZipFileToLocation(flSource, flTarget);
      System.out.println("Done");
      
    }
    catch (Exception ex){
      ex.printStackTrace();
    }
  }

  public static void unZipZipFileToLocation(File zipFile, File targetDir)
          throws IOException{
    if (! targetDir.isDirectory()){
      throw new Exception("Target is not a directory.");
    }
    FileInputStream flInStr = new FileInputStream(zipFile);
    try{
      ZipInputStream zis = new ZipInputStream(flInStr);
      try{
        ZipEntry entry = null;
        while((entry = zis.getNextEntry()) != null){
          String name = entry.getName();
          File newFile = new File(targetDir, name);
          if (entry.isDirectory() && ! newFile.exists() ){
            newFile.mkdirs();
          }
          else if (! entry.isDirectory() ){
            if (newFile.exists()){
              newFile.delete();
            }
            File parentDir = newFile.getParentFile();
            if (! parentDir.exists()){
              parentDir.mkdirs();
            }
            FileOutputStream stmOut = new FileOutputStream(newFile);
            try{
              simpleInputStreamToOutputStream(zis, stmOut);
            }
            finally{
              stmOut.close();
            }
          }
        }//end while.
      }
      finally{
        zis.close();
      }
    }
    finally{
      flInStr.close();
    }  
  }


  private static void simpleInputStreamToOutputStream(InputStream stmIn, OutputStream stmOut)
          throws IOException{

    byte[] buffer = null;
    int iBufferSize = 4096;
    buffer = new byte[iBufferSize];

    boolean bKeepStreaming = true;
    while (bKeepStreaming){
      int iBytes = stmIn.read(buffer);
      if (iBytes == -1){
        bKeepStreaming = false;
      }
      else{
        stmOut.write(buffer, 0, iBytes);
      }//end else some bytes returned.
    }//end while
  }


}

   
    
    
    
    
    
    
  
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.Creating a ZIP File
29.Listing the Contents of a ZIP File
30.Retrieving a Compressed File from a ZIP File
31.Calculating the Checksum of a Byte Array (Compute Adler-32 checksum)
32.Compute CRC-32 checksum
33.Calculating the Checksum of a File
34.Compress string(byte array) by Deflater
35.Use Java code to zip a folder
36.Uses Zip compression to compress any number of files given on the command line
37.Load zip file and scan zip file
38.Reading the Contents of a ZIP File
39.UnZip -- print or unzip a JAR or PKZIP file using java.util.zip
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.
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.