java压缩文件和解压文件

package cn.eeepay.pub.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

import cn.toruk.pub.Log;

public class ZipUtils {

	/**
	 * @param inputFileName
	 *            输入一个文件夹
	 * @param zipFileName
	 *            输出一个压缩文件夹,打包后文件名字
	 * @throws Exception
	 */
	public static void zip(String inputFileName, String zipFileName)
			throws Exception {
		zip(zipFileName, new File(inputFileName));
	}

	private static void zip(String zipFileName, File inputFile)
			throws Exception {
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
				zipFileName));
		out.setEncoding("UTF-8");// 解决linux乱码 根据linux系统的实际编码设置,可以使用命令
		// vi/etc/sysconfig/i18n 查看linux的系统编码
		zip(out, inputFile, "");
		out.close();
	}

	private static void zip(ZipOutputStream out, File f, String base)
			throws Exception {
		if (f.isDirectory()) { // 判断是否为目录
			File[] fl = f.listFiles();
			// out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
			// out.putNextEntry(new ZipEntry(base + "/"));
			ZipEntry zipEntry = new ZipEntry(base
					+ System.getProperties().getProperty("file.separator"));
			zipEntry.setUnixMode(755);// 解决linux乱码
			out.putNextEntry(zipEntry);
			// base = base.length() == 0 ? "" : base + "/";
			base = base.length() == 0 ? "" : base
					+ System.getProperties().getProperty("file.separator");
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base + fl[i].getName());
			}
		} else { // 压缩目录中的所有文件
			// out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
			ZipEntry zipEntry = new ZipEntry(base);
			zipEntry.setUnixMode(644);// 解决linux乱码
			out.putNextEntry(zipEntry);
			FileInputStream in = new FileInputStream(f);
			int b;
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
		}
	}

	public static void unzip(String sourceZip, String destDir) throws Exception {
		try {
			Project p = new Project();
			Expand e = new Expand();
			e.setProject(p);
			e.setSrc(new File(sourceZip));
			e.setOverwrite(false);
			e.setDest(new File(destDir));
			e.setEncoding("GBK");
			e.execute();
		} catch (Exception e) {
			throw e;
		}
	}

	public static void unZip(String zipFile, String outputFolder)
			throws Exception {
		Log.print("解压缩文件开始.........");
		byte[] buffer = new byte[1024];
		String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp",
				"txt", "xls", "zip" };// 允许解压出来的文件类型
		File folder = new File(outputFolder);
		if (!folder.exists()) {
			folder.mkdir();
		}

		java.util.zip.ZipInputStream zis = new java.util.zip.ZipInputStream(
				new FileInputStream(zipFile));
		java.util.zip.ZipEntry ze = null;

		while ((ze = zis.getNextEntry()) != null) {
			String fileName = ze.getName();
			File newFile = new File(outputFolder + File.separator + fileName);
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)
					.toLowerCase();// 文件扩展名

			if (Arrays.<String> asList(fileTypes).contains(fileExt)) {
				new File(newFile.getParent()).mkdirs();

				FileOutputStream fos = new FileOutputStream(newFile);

				int len;
				while ((len = zis.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
				fos.close();

			} else {// 不允许解压出来的文件已文件夹形式展示
				newFile.mkdirs();
			}
		}
		zis.closeEntry();
		zis.close();
		Log.print("解压缩文件结束.........");
	}

	public static final int BUFFER = 1024;// 缓存大小

	/**
	 * @Title: compress
	 * @Description: 压缩处理
	 * @param
	 * @return void
	 */
	@SuppressWarnings("unchecked")
	public static void compress(String baseDir, String filePath)
			throws Exception {
		List fileList = getSubFiles(new File(baseDir));
		ZipOutputStream zos = new ZipOutputStream(
				new FileOutputStream(filePath));
		ZipEntry ze = null;
		byte[] buf = new byte[BUFFER];
		int readLen = 0;
		for (int i = 0; i < fileList.size(); i++) {
			File f = (File) fileList.get(i);
			ze = new ZipEntry(getAbsFileName(baseDir, f));
			ze.setSize(f.length());
			ze.setTime(f.lastModified());
			zos.putNextEntry(ze);
			InputStream is = new BufferedInputStream(new FileInputStream(f));
			while ((readLen = is.read(buf, 0, BUFFER)) != -1) {
				zos.write(buf, 0, readLen);
			}
			is.close();
		}
		zos.close();
	}

	/**
	 * @Title: decompress
	 * @Description: 解压缩处理
	 * @param
	 * @return void
	 */
	public static void decompress(String filePath, String destDir)
			throws Exception {
		decompress(new File(filePath), destDir);
	}

	/**
	 * @Title: decompress
	 * @Description: 解压缩处理
	 * @param
	 * @param zip
	 * @param
	 * @param destDir
	 * @param
	 * @throws Exception
	 * @return void
	 */
	@SuppressWarnings("unchecked")
	public static void decompress(File zip, String destDir) throws Exception {
		destDir = destDir.endsWith("//") ? destDir : destDir + "//";
		byte b[] = new byte[BUFFER];
		int length;
		ZipFile zipFile;
		zipFile = new ZipFile(zip);
		Enumeration enumeration = zipFile.getEntries();
		ZipEntry zipEntry = null;

		while (enumeration.hasMoreElements()) {
			zipEntry = (ZipEntry) enumeration.nextElement();
			File loadFile = new File(destDir + zipEntry.getName());

			if (zipEntry.isDirectory()) {
				// 这段都可以不要,因为每次都貌似从最底层开始遍历的
				loadFile.mkdirs();
			} else {
				if (!loadFile.getParentFile().exists())
					loadFile.getParentFile().mkdirs();

				OutputStream outputStream = new FileOutputStream(loadFile);
				InputStream inputStream = zipFile.getInputStream(zipEntry);

				while ((length = inputStream.read(b)) > 0)
					outputStream.write(b, 0, length);
				inputStream.close();
				outputStream.close();
			}
		}
		zipFile.close();
	}

	/**
	 * 给定根目录,返回另一个文件名的相对路径,用于zip文件中的路径.
	 * 
	 * @param baseDir
	 *            java.lang.String 根目录
	 * @param realFileName
	 *            java.io.File 实际的文件名
	 * @return 相对文件名
	 */
	private static String getAbsFileName(String baseDir, File realFileName) {
		File real = realFileName;
		File base = new File(baseDir);
		String ret = real.getName();
		while (true) {
			real = real.getParentFile();
			if (real == null)
				break;
			if (real.equals(base))
				break;
			else
				ret = real.getName() + "/" + ret;
		}
		return real.getName() + "/" + ret;
	}

	/**
	 * 取得指定目录下的所有文件列表,包括子目录
	 * 
	 * @param baseDir
	 *            File 指定的目录
	 * @return 包含java.io.File的List
	 */
	@SuppressWarnings("unchecked")
	private static List getSubFiles(File baseDir) {
		List ret = new ArrayList();
		File[] tmp = baseDir.listFiles();
		for (int i = 0; i < tmp.length; i++) {
			if (tmp[i].isFile())
				ret.add(tmp[i]);
			if (tmp[i].isDirectory())
				ret.addAll(getSubFiles(tmp[i]));
		}
		return ret;
	}

	public static void main(String[] args) {
		try {
			// unZip("E:\\batch\\pics.zip", "E:\\batch");
			// ZipUtils.decompress("f:\\测试父目录.zip", "F:\\TDDOWNLOAD");;
			unzip("f:\\测试父目录.zip", "F:\\TDDOWNLOAD");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

你可能感兴趣的:(java压缩文件和解压文件)