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.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

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

public class Main {

    public static List<File> unzip(File zip, File toDir) throws IOException {
        ZipFile zf = null;
        List<File> files = null;
        try {
            zf = new ZipFile(zip);
            files = new ArrayList<File>();
            Enumeration<?> entries = zf.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                if (entry.isDirectory()) {
                    new File(toDir, entry.getName()).mkdirs();
                    continue;
                }

                InputStream input = null;
                OutputStream output = null;
                try {
                    File f = new File(toDir, entry.getName());
                    input = zf.getInputStream(entry);
                    output = new FileOutputStream(f);
                    copy(input, output);
                    files.add(f);
                } finally {
                    closeQuietly(output);
                    closeQuietly(input);
                }
            }
        } finally {
            if (zf != null) {
                zf.close();
            }
        }
        return files;
    }

    private static int copy(InputStream input, OutputStream output) throws IOException {
        long count = copyStream(input, output);
        if (count > Integer.MAX_VALUE) {
            return -1;
        }
        return (int) count;
    }

    private static void closeQuietly(OutputStream output) {
        try {
            if (output != null) {
                output.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }

    private static void closeQuietly(InputStream input) {
        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }

    private static long copyStream(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[1024];
        long count = 0;
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }
}