package com.qmth.jkserver.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.qmth.jkserver.constant.SystemConstant;
import org.apache.commons.io.IOUtils;

/**
 * zip 压缩工具类
 * 
 * @author tianjun
 *
 */
public class ZipUtils {

	private static byte[] BYTE = new byte[1024];

	public static void doZip(File zip, File src) throws IOException {
		doZip(zip, new File[] { src });
	}

	public static void doZip(File zip, File[] srcs) throws IOException {
		doZip(zip, Arrays.asList(srcs));
	}

	public static void doZip(File zip, List<File> srcs) throws IOException {
		ZipOutputStream zipOutputStream = null;
		OutputStream oStream = null;
		try {
			if (!zip.exists()) {
				zip.createNewFile();
			}
			oStream = new FileOutputStream(zip);
			zipOutputStream = new ZipOutputStream(oStream, Charset.forName(SystemConstant.CHARSET_NAME));
			for (File src : srcs) {
				doZip(zipOutputStream, src, "");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (zipOutputStream != null) {
				IOUtils.closeQuietly(zipOutputStream);
			}
			if (oStream != null) {
				IOUtils.closeQuietly(oStream);
			}
		}

	}

	public static void doZip(ZipOutputStream zipOutputStream, File src, String path) throws IOException {
		System.out.println("@@dozip src:" + src.getAbsolutePath());
		if (!"".equals(path) && !path.endsWith(File.separator)) {
			path += File.separator;
		}
		if (src.isDirectory()) {
			File[] files = src.listFiles();
			if (files.length == 0) {
				zipOutputStream.putNextEntry(new ZipEntry(path + src.getName() + File.separator));
				zipOutputStream.closeEntry();
			} else {
				for (File file : files) {
					doZip(zipOutputStream, file, path + src.getName());
				}
			}
		} else {
			InputStream is = new FileInputStream(src);
			zipOutputStream.putNextEntry(new ZipEntry(path + src.getName()));
			int len = 0;
			while ((len = is.read(BYTE)) > 0) {
				zipOutputStream.write(BYTE, 0, len);
			}
			IOUtils.closeQuietly(is);
			zipOutputStream.closeEntry();
		}
	}

	/**
	 * test
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		File file = new File("E:\\11111111");
		File zip = new File("C:\\Users\\tianjun\\Desktop\\tj20171103.zip");
		doZip(zip, file);
	}
}
