Home  >  Core Java

Example of ZipInputStream in Java

By Arvind Rai, February 09, 2013
We will discuss how to read a zip file in java. Java provides ZipInputStream class. That can understand zip coding. Read zip file by FileInputStream. Create ZipInputStream object with FileInputStream object. getNextEntry method returns ZipEntry object. This object gives the file name which has been zipped. Now write the data in the file returned by ZipEntry object.
package com.concretepage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipInputStreamTest {

    public static void main(String... args) throws IOException{

        // directory to read zip file and to write extracted file
        String dir="D:/page/";
        // read zip file as input stream
        InputStream is= new FileInputStream(dir+"file.zip");
        //zip is read by ZipInputStream
        ZipInputStream zis= new ZipInputStream(is);
        // now write zip file in extracted file
        ZipEntry ze;
        byte[] buff = new byte[1024];
        while((ze=zis.getNextEntry())!=null){
            // get file name
            FileOutputStream fos= new FileOutputStream(dir+ze.getName());
            int l=0;
            // write buffer to file
            while((l=zis.read(buff))>0){
                fos.write(buff,0, l);
            }
        }
        zis.close();
    }
}
After program is run, check the file in specified directory, we will be able to see file read from zip file.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us