Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//it under the terms of the GNU Affero General Public License as published by

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

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

public class Main {
    /**
     * creates azip file from an directory with all subfolders
     * @param dir
     * @param zipFileName
     * @throws IOException
     */
    public static void createZipFile(String dir, String zipFileName) throws IOException {
        String dirFile = dir + "/" + zipFileName;
        ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(dirFile)));
        try {
            zipDir(dir, zipOut, zipFileName);
        } finally {
            zipOut.close();
        }
    }

    /**
     * zips a directory
     * @param dir2zip
     * @param zipOut
     * @param zipFileName
     * @throws IOException
     */
    private static void zipDir(String dir2zip, ZipOutputStream zipOut, String zipFileName) throws IOException {
        File zipDir = new File(dir2zip);
        // get a listing of the directory content
        String[] dirList = zipDir.list();
        byte[] readBuffer = new byte[2156];
        int bytesIn = 0;
        // loop through dirList, and zip the files
        for (int i = 0; i < dirList.length; i++) {
            File f = new File(zipDir, dirList[i]);
            if (f.isDirectory()) {
                // if the File object is a directory, call this
                // function again to add its content recursively
                String filePath = f.getPath();
                zipDir(filePath, zipOut, zipFileName);
                // loop again
                continue;
            }

            if (f.getName().equals(zipFileName)) {
                continue;
            }
            // if we reached here, the File object f was not a directory
            // create a FileInputStream on top of f
            final InputStream fis = new BufferedInputStream(new FileInputStream(f));
            try {
                ZipEntry anEntry = new ZipEntry(f.getPath().substring(dir2zip.length() + 1));
                // place the zip entry in the ZipOutputStream object
                zipOut.putNextEntry(anEntry);
                // now write the content of the file to the ZipOutputStream
                while ((bytesIn = fis.read(readBuffer)) != -1) {
                    zipOut.write(readBuffer, 0, bytesIn);
                }
            } finally {
                // close the Stream
                fis.close();
            }
        }
    }
}