Powered By Blogger

Friday, October 26, 2012

Simple Java Program to Read Zip Files


This program takes a Zip File Name as input ( filename matchin regex '*.zip' )
'read()' method opens a ZipFileInputStream and reads each ZipEntry. A zipEntry is a file constituent of a zipFile. for E.g : if a zipFile name = =myzip.zip contains three files, namely :
file1.txt, file2.png, file.java, then myzip.zip has three ZipEntries.

Bytes contents of each Entry is written to a ByteArrayOutput stream and saved in a HashMap.
ZipInputStream and ByteArrayOutput streams are then closed


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipFileReader {

    private File zipFile;
   
    public ZipFileReader( File zipFile ) {
        this.zipFile = zipFile;
    }

    /**
     *
     * @return
     * @throws IOException
     */
    public Map read( ) throws IOException {

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        Map byteMap = new HashMap();
       
        byte[] buffer = new byte[4096];
        ZipEntry entry = null;
   
        while ((entry = zis.getNextEntry()) != null) {
           
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            System.out.println("Extracting: " + entry);
            int numBytes;
   
            while ((numBytes = zis.read(buffer, 0, buffer.length)) != -1)
                bos.write(buffer, 0, numBytes);

            zis.closeEntry();

bos.close();
                       
            byteMap.put( entry.getName(), bos.toByteArray() );
            }
        return byteMap;
    }
   
  }

No comments:

Post a Comment