Tuesday, 8 March 2016

EXTRACTING A ZIP FILE IN JAVA

in this tutorial we are going to see how to extract a zip file using java. there are two ways to extract zip files

1)zipinputstream
2)zipfile

here we use the zip file

package zip;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Multizipcreation {

    public static void main(String[] args) {
        File file = new File("/home/solomon/pdf.zip");
        try {
            byte[] buffer = new byte[1024];
            ZipFile zipFile = new ZipFile(file);
            File outputfolder = new File(file.getParent()+File.separator+"op");
            if(!outputfolder.exists()){
                outputfolder.mkdirs();
            }
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while(entries.hasMoreElements()){
             ZipEntry entry = entries.nextElement();
             InputStream is = zipFile.getInputStream(entry);
             extract(is,entry,outputfolder);
           
            }
           
            zipFile.close();
       
           
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
               

    }

    private static void extract(InputStream is, ZipEntry entry,File op) {
     try {
       
        FileOutputStream fos = new FileOutputStream(op+File.separator+entry.getName());

       
        int i;
        while((i=is.read())>-1){
        fos.write(i);
        }
        fos.close();
       
       
    } catch ( IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
       
    }

}

No comments:

Post a Comment