Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.InputStream;

import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Main {
    public static void unzip(final File zipFile, final File destFolder) {
        try {
            unzip(new FileInputStream(zipFile), destFolder);
        } catch (Exception ex) {
            throw new RuntimeException(
                    "Cannot unzip " + zipFile.getAbsolutePath() + " to " + destFolder.getAbsolutePath(), ex);
        }
    }

    public static void unzip(final InputStream input, final File destFolder) {
        try {
            byte[] buffer = new byte[4096];
            int read;
            ZipInputStream is = new ZipInputStream(input);
            ZipEntry entry;
            while ((entry = is.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    String fileName = entry.getName();
                    File fileFolder = destFolder;
                    int lastSep = entry.getName().lastIndexOf(File.separatorChar);
                    if (lastSep != -1) {
                        String dirPath = fileName.substring(0, lastSep);
                        fileFolder = new File(fileFolder, dirPath);
                        fileName = fileName.substring(lastSep + 1);
                    }
                    fileFolder.mkdirs();
                    File file = new File(fileFolder, fileName);
                    FileOutputStream os = new FileOutputStream(file);
                    while ((read = is.read(buffer)) != -1) {
                        os.write(buffer, 0, read);
                    }
                    os.flush();
                    os.close();
                }
            }
            is.close();
        } catch (Exception ex) {
            throw new RuntimeException("Cannot unzip stream to " + destFolder.getAbsolutePath(), ex);
        }
    }
}