Unzip files to path. - Java File Path IO

Java examples for File Path IO:Zip File

Description

Unzip files to path.

Demo Code


//package com.java2s;
import java.io.*;

import java.util.Enumeration;

import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Main {
    /**//from ww w. j  a  v a2s  .c  o m
     * Unzip files to path.
     * 
     * @param zipFileName the zip file name
     * @param fileExtractPath the file extract path
     * @throws IOException Signals that an I/O exception has occurred.
     */
    public static void unzipFilesToPath(String jarPath,
            String destinationDir) throws IOException {
        File file = new File(jarPath);
        JarFile jar = new JarFile(file);

        // fist get all directories,
        // then make those directory on the destination Path
        for (Enumeration<JarEntry> enums = jar.entries(); enums
                .hasMoreElements();) {
            JarEntry entry = (JarEntry) enums.nextElement();

            String fileName = destinationDir + File.separator
                    + entry.getName();
            File f = new File(fileName);

            if (fileName.endsWith("/")) {
                f.mkdirs();
            }

        }

        //now create all files
        for (Enumeration<JarEntry> enums = jar.entries(); enums
                .hasMoreElements();) {
            JarEntry entry = (JarEntry) enums.nextElement();

            String fileName = destinationDir + File.separator
                    + entry.getName();
            File f = new File(fileName);

            if (!fileName.endsWith("/")) {
                InputStream is = jar.getInputStream(entry);
                FileOutputStream fos = new FileOutputStream(f);

                // write contents of 'is' to 'fos'
                while (is.available() > 0) {
                    fos.write(is.read());
                }

                fos.close();
                is.close();
            }
        }

        try {
            jar.close();
        } catch (Exception e) {

        }
    }
}

Related Tutorials