Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;

import java.net.URL;

import java.util.Enumeration;

import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Main {
    /**
     * URL _dest has to use "file://" as protocol !!!
     * @param _url
     * @param _dest
     */
    public static void unzip(URL _url, URL _dest) {
        unzip(_url, _dest, false);
    }

    public static void unzip(URL _url, URL _dest, boolean _remove_top) {
        int BUFFER_SZ = 2048;
        File file = new File(_url.getPath());

        String dest = _dest.getPath();
        new File(dest).mkdir();

        try {
            ZipFile zip = new ZipFile(file);
            Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();

            // Process each entry
            while (zipFileEntries.hasMoreElements()) {
                // grab a zip file entry
                ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
                String currentEntry = entry.getName();

                if (_remove_top)
                    currentEntry = currentEntry.substring(currentEntry.indexOf('/'), currentEntry.length());

                File destFile = new File(dest, currentEntry);
                //destFile = new File(newPath, destFile.getName());
                File destinationParent = destFile.getParentFile();

                // create the parent directory structure if needed
                destinationParent.mkdirs();

                if (!entry.isDirectory()) {
                    BufferedInputStream is;
                    is = new BufferedInputStream(zip.getInputStream(entry));
                    int currentByte;
                    // establish buffer for writing file
                    byte data[] = new byte[BUFFER_SZ];

                    // write the current file to disk
                    FileOutputStream fos = new FileOutputStream(destFile);
                    BufferedOutputStream dst = new BufferedOutputStream(fos, BUFFER_SZ);

                    // read and write until last byte is encountered
                    while ((currentByte = is.read(data, 0, BUFFER_SZ)) != -1) {
                        dst.write(data, 0, currentByte);
                    }
                    dst.flush();
                    dst.close();
                    is.close();
                }
                /*
                if (currentEntry.endsWith(".zip"))
                {
                // found a zip file, try to open
                extractFolder(destFile.getAbsolutePath());
                }*/
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}