Wednesday, June 1, 2011

How to Extract contents of a zip file

This example shows how to extract a zipfile containing one file (or entry).  The name of the zip file is 'compressed.zip' and we want to write the contents to a file called 'extracted.txt'. We start by opening an input stream to the compressed file and an output stream to the file where we want the content to be extracted. After that we get the next entry of the zip file (and the only entry in this case) - test so it's not null, and then start  reading the contents from the input stream and writing each chunk read to the output stream. As usual we should clean up properly afterwards so we close the input and output streams.

package org.best.example.compression
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Main {

    /**
     * Extracts a zip file
     */

    public void extractZipFile() {
       
        try {
            String zipFileName = "compressed.zip";
            String extractedFileName = "extracted.txt";
           
            //Create input and output streams
            ZipInputStream inStream = new ZipInputStream(new FileInputStream(zipFileName));
            OutputStream outStream = new FileOutputStream(extractedFileName);
           
            ZipEntry entry;
            byte[] buffer = new byte[1024];
            int nrBytesRead;
           
            //Get next zip entry and start reading data
            if ((entry = inStream.getNextEntry()) != null) {
                while ((nrBytesRead = inStream.read(buffer)) > 0) {
                    outStream.write(buffer, 0, nrBytesRead);
                }
            }
                   
            //Finish off by closing the streams
            outStream.close();
            inStream.close();
           
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().extractZipFile();
    }
   
}
 

No comments: