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.*;

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

public class Main {
    /***
     * Extract zipfile to outdir with complete directory structure
     * disclaimer, I didn't wrote that ...
     * @param zipfile Input .zip file
     * @param outdir Output directory
     */
    public static void extract(File zipfile, File outdir) {
        // todo: replace with more trustful method
        try {
            ZipInputStream zin = new ZipInputStream(new FileInputStream(zipfile));
            ZipEntry entry;
            String name, dir;
            while ((entry = zin.getNextEntry()) != null) {
                name = entry.getName();
                if (entry.isDirectory()) {
                    mkdirs(outdir, name);
                    continue;
                }
                dir = dirpart(name);
                if (dir != null) {
                    mkdirs(outdir, dir);
                }
                extractFile(zin, outdir, name);
            }
            zin.close();
        } catch (IOException err) {
            throw new RuntimeException("Unable to extract quiz", err);
        }
    }

    private static void mkdirs(File outdir, String path) {
        File d = new File(outdir, path);
        if (!d.exists()) {
            //noinspection ResultOfMethodCallIgnored
            d.mkdirs();
        }
    }

    private static String dirpart(String name) {
        int s = name.lastIndexOf("/");
        return s == -1 ? null : name.substring(0, s);
    }

    private static void extractFile(ZipInputStream in, File outdir, String name) throws IOException {
        byte[] buffer = new byte[4096];

        final File file = new File(outdir, name);
        try (final FileOutputStream fos = new FileOutputStream(file)) {
            try (final BufferedOutputStream out = new BufferedOutputStream(fos)) {
                int count;
                while ((count = in.read(buffer)) != -1) {
                    out.write(buffer, 0, count);
                }
            }
        }
    }
}