Java Zip Files makeZip(String[] inFilePaths, String zipFilePath)

Here you can find the source of makeZip(String[] inFilePaths, String zipFilePath)

Description

make Zip

License

Apache License

Declaration

public static void makeZip(String[] inFilePaths, String zipFilePath) throws Exception 

Method Source Code

//package com.java2s;
/**/*  www.  j a  va  2 s .  c  o m*/
 *  Copyright (c) 2014 http://www.lushapp.wang
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 */

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    public static final int BUFFER_SIZE_DIFAULT = 1024;

    public static void makeZip(String[] inFilePaths, String zipFilePath) throws Exception {
        File[] inFiles = new File[inFilePaths.length];
        for (int i = 0; i < inFilePaths.length; i++) {
            inFiles[i] = new File(inFilePaths[i]);
        }
        makeZip(inFiles, zipFilePath);
    }

    public static void makeZip(File[] inFiles, String zipFilePath) throws Exception {
        ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFilePath)));
        for (int i = 0; i < inFiles.length; i++) {
            doZipFile(zipOut, inFiles[i], inFiles[i].getParent());
        }
        zipOut.flush();
        zipOut.close();
    }

    private static void doZipFile(ZipOutputStream zipOut, File file, String dirPath)
            throws FileNotFoundException, IOException {
        if (file.isFile()) {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            String zipName = file.getPath().substring(dirPath.length());
            while (zipName.charAt(0) == '\\' || zipName.charAt(0) == '/') {
                zipName = zipName.substring(1);
            }
            ZipEntry entry = new ZipEntry(zipName);
            zipOut.putNextEntry(entry);
            byte[] buff = new byte[BUFFER_SIZE_DIFAULT];
            int size;
            while ((size = bis.read(buff, 0, buff.length)) != -1) {
                zipOut.write(buff, 0, size);
            }
            zipOut.closeEntry();
            bis.close();
        } else {
            File[] subFiles = file.listFiles();
            for (File subFile : subFiles) {
                doZipFile(zipOut, subFile, dirPath);
            }
        }
    }
}

Related

  1. addToZipFile(InputStream source, String entryName, ZipOutputStream zos)
  2. addToZipFile(String fileName, ZipOutputStream zos)
  3. fileToZip(File file, File zipFile)
  4. fileToZipFile(File toZip, File output)
  5. makeZip(File dir, File zipFile)
  6. makeZipBinary(Map instance, String fileNameSeperator)