Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

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

public class Main {
    public static final int BUFFER_SIZE = 8192;

    /**
     * Extracts the whole contents of in_file to out_dir.
     * @param in_file A file object pointing to a zip file.
     * @param out_dir A directory where the contents of the file should be placed.
     * @throws IOException if there's a problem with one of the files
     */
    public static void zipExtract(File in_file, File out_dir) throws IOException {
        InputStream is = new FileInputStream(in_file);
        BufferedInputStream bis = new BufferedInputStream(is, BUFFER_SIZE);
        zipExtract(bis, out_dir);
    }

    /**
     * Reads the in_stream and extracts them to out_dir.
     * @param in_stream Input stream corresponding to the zip file.
     * @param out_dir Output directory for the zip file contents.
     * @throws IOException
     */
    public static void zipExtract(InputStream in_stream, File out_dir) throws IOException {
        if (!out_dir.exists()) {
            if (!out_dir.mkdirs()) {
                throw new IOException("Could not create output directory: " + out_dir.getAbsolutePath());
            }
        }
        ZipInputStream zis = new ZipInputStream(in_stream);
        ZipEntry ze;
        byte[] buffer = new byte[BUFFER_SIZE];
        int count;
        while ((ze = zis.getNextEntry()) != null) {
            if (ze.isDirectory()) {
                File fmd = new File(out_dir.getAbsolutePath() + "/" + ze.getName());
                fmd.mkdirs();
                continue;
            }
            FileOutputStream fout = new FileOutputStream(out_dir.getAbsolutePath() + "/" + ze.getName());
            while ((count = zis.read(buffer)) != -1) {
                fout.write(buffer, 0, count);
            }

            fout.close();
            zis.closeEntry();
        }
        zis.close();
    }
}