Sunday, February 17, 2008

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.
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;

/**
 *
 * @author javadb.com
 */
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();
    }
    
}

 
Blogger Template Layout Design by [ METAMUSE ] : Code Name Gadget 1.1 Power By freecode-frecode.blogger.com & blogger.com Programming Blogs - BlogCatalog Blog Directory