package com.jkcredit.invoice.util;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
/**
 * ZipUtils
 * 
 * @author ZENG.XIAO.YAN
 * @date 2017年11月19日 下午7:16:08
 * @version v1.0
 */
public class ZipUtils {
	private static final int BUFFEREDSIZE = 1024;
	/**
	 * 压缩文件
	 *
	 * @param zipFileName
	 *      保存的压缩包文件路径
	 * @param filePath
	 *      需要压缩的文件夹或者文件路径
	 * @param isDelete
	 *      是否删除源文件
	 * @throws Exception
	 */
	public static void zip(String zipFileName, String filePath, boolean isDelete) throws Exception {
		zip(zipFileName, new File(filePath), isDelete);
	}
	/**
	 * 压缩文件
	 *
	 * @param zipFileName
	 *      保存的压缩包文件路径
	 * @param inputFile
	 *      需要压缩的文件夹或者文件
	 * @param isDelete
	 *      是否删除源文件
	 * @throws Exception
	 */
	public static void zip(String zipFileName, File inputFile, boolean isDelete) throws Exception {
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
		if (!inputFile.exists()) {
			throw new FileNotFoundException("在指定路径未找到需要压缩的文件！");
		}
		zip(out, inputFile, "", isDelete);
		out.close();
	}
	/**
	 * 递归压缩方法
	 *
	 * @param out
	 *      压缩包输出流
	 * @param inputFile
	 *      需要压缩的文件
	 * @param base
	 *      压缩的路径
	 * @param isDelete
	 *      是否删除源文件
	 * @throws Exception
	 */
	private static void zip(ZipOutputStream out, File inputFile, String base, boolean isDelete) throws Exception {
		// 如果是目录
		if (inputFile.isDirectory()) {
			File[] inputFiles = inputFile.listFiles();
			out.putNextEntry(new ZipEntry(base + "/"));
			base = base.length() == 0 ? "" : base + "/";
			for (int i = 0; i < inputFiles.length; i++) {
				zip(out, inputFiles[i], base + inputFiles[i].getName(), isDelete);
			}
		} else { // 如果是文件
			if (base.length() > 0) {
				out.putNextEntry(new ZipEntry(base));
			} else {
				out.putNextEntry(new ZipEntry(inputFile.getName()));
			}
			FileInputStream in = new FileInputStream(inputFile);
			try {
				int len;
				byte[] buff = new byte[BUFFEREDSIZE];
				while ((len = in.read(buff)) != -1) {
					out.write(buff, 0, len);
				}
			} catch (IOException e) {
				throw e;
			} finally {
				in.close();
			}
		}
		if (isDelete) {
			inputFile.delete();
		}
	}
// public static void main(String[] args) {
//   ZipUtil cpr = new ZipUtil();
//   try {
//     cpr.zip("C:/Users/Lenovo User/Desktop/test中文.zip", "C:/Users/Lenovo User/Desktop/新建文件夹", false);
//     cpr.unZip("C:/Users/Lenovo User/Desktop/test中文.zip", "C:/Users/Lenovo User/Desktop/新建文件夹2", false);
//   } catch (Exception e) {
//     e.printStackTrace();
//   }
//
// }
}