Powered By Blogger

Friday, October 26, 2012

Simple Java Program to Write to a Zip File.

This Program takes a Zip file Directory and a Zip file name as Input.
'writeAsZip()' method writes an Array of Bytes as a Zip Entry to the Zip file.
Suppose a zip file 'D:\\test\\cb-1-zip.zip' is has two constituents, namely : 'a.txt' and 'b.png'
This zip File is read and contents stored in a hashMap by 'ZipFileReader'.The size of hashmap is now 2, containing bytes[] of a.txt and b.png

'write()' method takes bytes[] array and name of the file entry to be written to t he Zip file.

Each entry is closed by calling ZipOutputStream#closeEntry() method. Once closeEntry() is called , ZipOutputStream is ready for addition of a new Zip Entry.

Finally ZipOutpurStream#close() method is called. This method finally closes the stream
If the program misses to call 'close()' then a fautly zip file is written to the file system, that is corrupt and perhaps cannot be used. ZipOutpurStream#close() adds the required stream terminating characters.


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ZipFileWriter {

    private String zipDir;
   
    private String zipFilename; // ends in .zip
   
    private static String FS = System.getProperty("file.separator" );
   
    public ZipFileWriter( String zipDir, String zipFilename ) {
        this.zipDir = zipDir;
        this.zipFilename = zipFilename;
    }
   
    /**
    }
     *
     * @return
     * @throws IOException
     */
    public void writeAsZip( byte[] bytesRead, String fileEntry ) throws IOException {

        String absoluteZipFIleName = zipDir + FS + zipFilename;
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(absoluteZipFIleName));
   
        ZipEntry entry = new ZipEntry( fileEntry );
        zos.putNextEntry( entry );
       
        zos.write(bytesRead);
       
        zos.closeEntry();       
        zos.close();
    }
   
    public void writeAsText( String filename, byte[] bytesRead ) throws IOException{
        FileOutputStream fos = new FileOutputStream( new File( zipDir +  FS + filename ));
        fos.write( bytesRead );
        fos.close();
    }


 public static void main(String[] args) throws Exception {
     String FS = System.getProperty("file.separator" );
      String zipDirRead = "D:\\test";
      String zipDirWrite = "D:\\test\\out";
      String zipFilename = "cb-1-zip.zip";
     
      
      File zipFile = new File ( zipDirRead + FS + zipFilename );
     
      ZipFileReader reader = new ZipFileReader( zipFile );
      Map map = reader.read();
   
      ZipFileWriter writer = new ZipFileWriter(zipDirWrite, zipFilename);
      Set set = map.keySet();
      Iterator iter = set.iterator();
      while ( iter.hasNext() ) {
         
         String key = iter.next();
          System.out.println("Writing file Entry :" + key );
          byte[] bytesread = map.get(key);
       
          writer.writeAsZip( bytesread, key );
          writer.writeAsText( key, bytesread );
      }
   
}

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