Extract All From Zip - Java File Path IO

Java examples for File Path IO:Zip File

Description

Extract All From Zip

Demo Code


//package com.java2s;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;

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

public class Main {
    public static void ExtractAllFromZip(ZipFile zf, File dest)
            throws IOException {
        if (!dest.isDirectory())
            throw new InvalidParameterException(
                    "Destination must be a directory!");
        Enumeration<? extends ZipEntry> entries = zf.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            //         System.out.println("Extracting " + entry.toString());
            ExtractFromZip(zf, entry, new File(dest, entry.getName()));
        }/* w w  w. ja  va  2 s  .  com*/
    }

    /**
     * Extracts entry from zf into dest
     * @param zf the zip file to extract from
     * @param entry the entry in the zip to extract
     * @param dest the destination to extract to
     */
    public static void ExtractFromZip(ZipFile zf, ZipEntry entry, File dest)
            throws IOException {
        if (entry.isDirectory()) {
            dest.mkdirs();
            return;
        }

        //if (!dest.getParentFile().exists())
        dest.getParentFile().mkdirs();

        if (!dest.exists())
            dest.createNewFile();

        int bufSize = 1024;

        InputStream is = zf.getInputStream(entry);
        BufferedInputStream in = new BufferedInputStream(is, bufSize);

        FileOutputStream fos = new FileOutputStream(dest);
        BufferedOutputStream out = new BufferedOutputStream(fos, bufSize);

        int count = 0;
        byte[] buffer = new byte[bufSize];
        while ((count = in.read(buffer, 0, buffer.length)) != -1) {
            out.write(buffer, 0, count);
        }
        out.flush();
        out.close();
        is.close();
    }
}

Related Tutorials