package com.qmth.qrzk.repository.utils;

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.io.OutputStream;
import java.util.Enumeration;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

/**
 * 将文件打包成ZIP压缩文件
 * 
 * @author zhong_hui
 * @since 2013-2-23 11:12
 */
public class CompressZIP {
	private static int BUFFER = 1024 * 10;

	private CompressZIP() {

	}

	/**
	 * 将存放在sourceFilePath目录下的源文件,打包成fileName名称的ZIP文件,并存放到zipFilePath。
	 * 
	 * @param sourceFilePath
	 *            待压缩的文件路径
	 * @param zipFilePath
	 *            压缩后存放路径
	 * @param fileName
	 *            压缩后文件的名称
	 * @return flag
	 */
	public static boolean fileToZip(String sourceFilePath, String zipFilePath,
			String fileName) {
		boolean flag = false;
		File sourceFile = new File(sourceFilePath);
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		ZipOutputStream zos = null;

		if (!sourceFile.exists()) {
			System.out.println(">>>>>> 待压缩的文件目录：" + sourceFilePath
					+ " 不存在. <<<<<<");
		} else {
			try {
				File downFile=new File(zipFilePath);
				if(!downFile.exists()){
					downFile.mkdirs();
				}
				File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
				if (zipFile.exists())
					zipFile.delete();
				File[] sourceFiles = sourceFile.listFiles();
				if (null == sourceFiles || sourceFiles.length < 1) {
					System.out.println(">>>>>> 待压缩的文件目录：" + sourceFilePath
							+ " 里面不存在文件,无需压缩. <<<<<<");
				} else {
					zip(zipFilePath + "/" + fileName, sourceFilePath);
					flag = true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// 关闭流
				try {
					if (null != bis)
						bis.close();
					if (null != zos)
						zos.close();
					if (null != fos)
						fos.close();
					if (null != fis)
						fis.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		}

		return flag;
	}

	public static void zip(String zipedName, String zipPath) {
		File temp = new File(zipedName);

		// 如果指定路径不存在，就创建
		if (!temp.exists())
			new File(zipedName.substring(0, zipedName.lastIndexOf("/")))
					.mkdirs();
		try {
			ZipOutputStream out = new ZipOutputStream(
					new FileOutputStream(temp));
			// 设置压缩编码
			out.setEncoding("UTF-8");// 设置为UTF-8后在windows下就不会乱码了，如果要放到Linux或者Unix下就不要设置了

			File input = new File(zipPath);
			if (!input.isDirectory()) {
				out.putNextEntry(new ZipEntry(input.getName())); // 生成下一个压缩节点
				FileInputStream in = new FileInputStream(zipPath); // 读取文件内容
				int len;
				byte[] buf = new byte[BUFFER];
				while ((len = in.read(buf, 0, BUFFER)) != -1) {
					out.write(buf, 0, len); // 写入到压缩包
				}
				in.close();
			} else {
				zip(out, input, "");
			}
			out.flush();
			out.close();
		} catch (IOException io) {
			io.printStackTrace();
		}
	}

	private static void zip(ZipOutputStream out, File inputFile, String base) {
		try {
			if (inputFile.isDirectory()) { // 如果是文件夹，则获取下面的所有文件
				File[] fl = inputFile.listFiles();
				out.putNextEntry(new ZipEntry(base + "/"));// 此处要将文件写到文件夹中只用在文件名前加"/"再加文件夹名
				base = base.length() == 0 ? "" : base + "/";
				for (int i = 0; i < fl.length; i++) {
					zip(out, fl[i], base + fl[i].getName());
				}
			} else if (inputFile.getName().endsWith(".txt")) { // 如果是文件，则压缩
				out.putNextEntry(new ZipEntry(base)); // 生成下一个压缩节点
				FileInputStream in = new FileInputStream(inputFile); // 读取文件内容
				int len;
				byte[] buf = new byte[BUFFER];
				while ((len = in.read(buf, 0, BUFFER)) != -1) {
					out.write(buf, 0, len); // 写入到压缩包
				}
				in.close();
			} else {
				out.putNextEntry(new ZipEntry(base)); // 生成下一个压缩节点
				FileInputStream in = new FileInputStream(inputFile); // 读取文件内容
				int len;
				byte[] buf = new byte[BUFFER];
				while ((len = in.read(buf, 0, BUFFER)) != -1) {
					out.write(buf, 0, len); // 写入到压缩包
				}
				in.close();
			}

		} catch (IOException io) {
			io.printStackTrace();
		}
	}

	/**
	 * 解压到指定目录
	 * 
	 * @param zipPath
	 * @param descDir
	 * @author 钟辉
	 */
	public static void unZipFiles(String zipPath, String descDir) {
		try {
			unZipFiles(new File(zipPath), descDir);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 解压文件到指定目录
	 * 
	 * @param zipFile
	 * @param descDir
	 * @author 钟辉
	 */
	@SuppressWarnings("rawtypes")
	public static void unZipFiles(File zipFile, String descDir) throws IOException {
		File pathFile = new File(descDir);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
		ZipFile zip = new ZipFile(zipFile);
		InputStream in = null;
		
		for (Enumeration entries = zip.getEntries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			String zipEntryName = entry.getName();
			in = zip.getInputStream(entry);
			String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
			;
			// 判断路径是否存在,不存在则创建文件路径
			File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
			if (!file.exists()) {
				file.mkdirs();
			}
			// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
			if (new File(outPath).isDirectory()) {
				continue;
			}
			// 输出文件路径信息

			OutputStream out = new FileOutputStream(outPath);
			byte[] buf1 = new byte[1024];
			int len;
			while ((len = in.read(buf1)) > 0) {
				out.write(buf1, 0, len);
			}
			
			if(out!=null){
				out.flush();
				out.close();
			}
			
		}
		
		if(in!=null){
			in.close();
		}
		if(zip!=null){
			zip.close();
		}
	}

	/**
	 * 将文件打包成ZIP压缩文件,main方法测试
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// String sourceFilePath =
		// "G:\\公司项目\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\qrzk\\paper\\2";
		// String zipFilePath =
		// "G:\\公司项目\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\qrzk\\zip";
		// String fileName = "2";
		// boolean flag = CompressZIP.fileToZip(sourceFilePath, zipFilePath,
		// fileName);
		// if(flag) {
		// System.out.println(">>>>>> 文件打包成功. <<<<<<");
		// } else {
		// System.out.println(">>>>>> 文件打包失败. <<<<<<");
		// }
		String str = "D:/test/zip/upload/201012001/201012001.cdr";
		String[] s = str.split("/");
		System.out.println(s[s.length - 1]);
	}
}
