java对文件压缩与解压缩操作

1. 文件的压缩
/**
	 * 压缩文件,支持文件和目录
	 * @param srcFile 待压缩的文件
	 * @param desPathName 压缩后的文件名(带路径)
	 */
	public static void zip(File srcFile, String desPathName) {
		if (!srcFile.exists()) {
			log.error("文件{}不存在:", srcFile.getAbsolutePath());
			return;
		}
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(desPathName);
			CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32());
			ZipOutputStream out = new ZipOutputStream(cos);
			zipByType(srcFile, out, "");
			out.close();
		} catch (Exception e) {
			log.error("压缩文件异常:", e);
			return;
		}
	}
	/**
	 * 判断是目录还是文件,根据类型(文件/文件夹)执行不同的压缩方法
	 * @param file 待压缩的文件
	 * @param out 文件压缩流
	 * @param basedir 压缩文件里面的相对路径
	 */
	private static void zipByType(File file, ZipOutputStream out, String basedir) {
		/* 判断是目录还是文件 */
		if (file.isDirectory()) {
			zipDirectory(file, out, basedir);
		} else {
			zipFile(file, out, basedir);
		}
	}
	/**
	 * 压缩一个目录
	 * @param dir 待压缩的目录
	 * @param out 文件压缩流
	 * @param basedir 压缩文件里面的相对路径
	 */
	private static void zipDirectory(File dir, ZipOutputStream out, String basedir) {
		if (!dir.exists()) {
			log.error("文件{}不存在:", dir.getAbsolutePath());
			return;
		}
		File[] files = dir.listFiles();
		for (int i = 0; i < files.length; i++) {
			/* 递归 */
			zipByType(files[i], out, basedir + dir.getName() + "/");
		}
	}
	/**
	 * 压缩一个文件
	 * @param file 待压缩的文件
	 * @param out 压缩流
	 * @param basedir 压缩文件里面的相对路径
	 */
	private static void zipFile(File file, ZipOutputStream out, String basedir) {
		if (!file.exists()) {
			log.error("文件{}不存在", file.getAbsolutePath());
			return;
		}
		try {
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
			ZipEntry entry = new ZipEntry(basedir + file.getName());
			out.putNextEntry(entry);
			int count;
			byte data[] = new byte[8192];
			while ((count = bis.read(data, 0, data.length)) != -1) {
				out.write(data, 0, count);
			}
			bis.close();
		} catch (Exception e) {
			log.error("压缩文件异常:", e);
			return;
		}
	}

2. 文件的解压缩
/**
	 * 解压缩文件操作
	 * 
	 * @param srcPathName
	 *            被解压的压缩文件名(带路径)
	 * @param desPathName
	 *            解压后的目录
	 */
	public static void unzip(String zipFileName, String desPathName) {
		File zipFile = new File(zipFileName);
		unzip(zipFile, desPathName);
	}
	/**
	 * 解压缩文件操作
	 * 
	 * @param zipFile
	 *            被解压的压缩文件
	 * @param targetPath
	 *            解压后的目录
	 */
	public static void unzip(File zipFile, String targetPath) {
		if (!zipFile.exists()) {
			log.error("文件{}不存在", zipFile.getAbsolutePath());
		}
		try {
			File pathFile = new File(targetPath);
			if (!pathFile.exists()) {
				pathFile.mkdirs();
			}
			ZipFile zip = new ZipFile(zipFile);
			for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
				ZipEntry entry = (ZipEntry) entries.nextElement();
				
				String zipEntryName = entry.getName();
				InputStream in = zip.getInputStream(entry);
				String outPath = (targetPath + zipEntryName).replaceAll("\\*", "/");
				// 判断路径是否存在,不存在则创建文件路径
				if (outPath.indexOf('/') > 0) {
					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);
				}
				in.close();
				out.close();
			}
			zip.close();
		} catch (IOException e) {
			log.error("解压缩文件异常:", e);
			return;
		}
	}

3. 附工具类ZipUtil.java
package com.morris.util.file;
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 java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 文件的压缩与解压
 * @author Morris
 *
 */
public class ZipUtil {
	
	private static final transient Logger log = LoggerFactory.getLogger(ZipUtil.class);
	// ------------------------------压缩文件begin----------------------------------------
	/**
	 * 压缩文件,支持文件和目录
	 * @param srcPathName 被压缩的文件名(带路径),压缩到当前目录下
	 */
	public static void zip(String srcPathName) {
		zip(new File(srcPathName));
	}
	/**
	 * 执行压缩文件操作,支持文件和文件夹
	 * 
	 * @param srcFile 被压缩的文件,压缩到当前目录下
	 */
	public static void zip(File srcFile) {
		if (!srcFile.exists()) {
			log.info("文件{}不存在!", srcFile.getAbsolutePath());			
		}
		String desFileName = srcFile.getName();
		if (!srcFile.isDirectory()) {
			desFileName = desFileName.substring(0, desFileName.lastIndexOf("."));
		}
		desFileName += ".zip";
		String desFile = srcFile.getParent() + "/" + desFileName;
		zip(srcFile, desFile);
	}
	/**
	 * 执行压缩文件操作,支持文件和文件夹
	 * 
	 * @param srcPathName
	 *            被压缩的文件名(带路径)
	 * @param desPathName
	 *            压缩后的文件名(带路径)
	 */
	public static void zip(String srcPathName, String desPathName) {
		File srcFile = new File(srcPathName);
		zip(srcFile, desPathName);
	}
	/**
	 * 压缩文件,支持文件和目录
	 * @param srcFile 待压缩的文件
	 * @param desPathName 压缩后的文件名(带路径)
	 */
	public static void zip(File srcFile, String desPathName) {
		if (!srcFile.exists()) {
			log.error("文件{}不存在:", srcFile.getAbsolutePath());
			return;
		}
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(desPathName);
			CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32());
			ZipOutputStream out = new ZipOutputStream(cos);
			zipByType(srcFile, out, "");
			out.close();
		} catch (Exception e) {
			log.error("压缩文件异常:", e);
			return;
		}
	}
	/**
	 * 判断是目录还是文件,根据类型(文件/文件夹)执行不同的压缩方法
	 * @param file 待压缩的文件
	 * @param out 文件压缩流
	 * @param basedir 压缩文件里面的相对路径
	 */
	private static void zipByType(File file, ZipOutputStream out, String basedir) {
		/* 判断是目录还是文件 */
		if (file.isDirectory()) {
			zipDirectory(file, out, basedir);
		} else {
			zipFile(file, out, basedir);
		}
	}
	/**
	 * 压缩一个目录
	 * @param dir 待压缩的目录
	 * @param out 文件压缩流
	 * @param basedir 压缩文件里面的相对路径
	 */
	private static void zipDirectory(File dir, ZipOutputStream out, String basedir) {
		if (!dir.exists()) {
			log.error("文件{}不存在:", dir.getAbsolutePath());
			return;
		}
		File[] files = dir.listFiles();
		for (int i = 0; i < files.length; i++) {
			/* 递归 */
			zipByType(files[i], out, basedir + dir.getName() + "/");
		}
	}
	/**
	 * 压缩一个文件
	 * @param file 待压缩的文件
	 * @param out 压缩流
	 * @param basedir 压缩文件里面的相对路径
	 */
	private static void zipFile(File file, ZipOutputStream out, String basedir) {
		if (!file.exists()) {
			log.error("文件{}不存在", file.getAbsolutePath());
			return;
		}
		try {
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
			ZipEntry entry = new ZipEntry(basedir + file.getName());
			out.putNextEntry(entry);
			int count;
			byte data[] = new byte[8192];
			while ((count = bis.read(data, 0, data.length)) != -1) {
				out.write(data, 0, count);
			}
			bis.close();
		} catch (Exception e) {
			log.error("压缩文件异常:", e);
			return;
		}
	}
	// ------------------------------压缩文件end------------------------------------------
	// ------------------------------解压缩文件begin--------------------------------------
	/**
	 * 解压缩文件操作,解压到到当前目录下
	 * 
	 * @param zipFile
	 *            被解压的压缩文件名(带路径)
	 */
	public static void unzip(String zipFileName) {
		File zipFile = new File(zipFileName);
		unzip(zipFile);
	}
	/**
	 * 解压缩文件操作,解压到到当前目录下
	 * 
	 * @param zipFile
	 *            被解压的压缩文件
	 */
	public static void unzip(File zipFile) {
		if (!zipFile.exists()) {
			log.error("文件{}不存在", zipFile.getAbsolutePath());
		}
		String targetPath = zipFile.getParent() + "/";
		unzip(zipFile, targetPath);
	}
	/**
	 * 解压缩文件操作
	 * 
	 * @param srcPathName
	 *            被解压的压缩文件名(带路径)
	 * @param desPathName
	 *            解压后的目录
	 */
	public static void unzip(String zipFileName, String desPathName) {
		File zipFile = new File(zipFileName);
		unzip(zipFile, desPathName);
	}
	/**
	 * 解压缩文件操作
	 * 
	 * @param zipFile
	 *            被解压的压缩文件
	 * @param targetPath
	 *            解压后的目录
	 */
	public static void unzip(File zipFile, String targetPath) {
		if (!zipFile.exists()) {
			log.error("文件{}不存在", zipFile.getAbsolutePath());
		}
		try {
			File pathFile = new File(targetPath);
			if (!pathFile.exists()) {
				pathFile.mkdirs();
			}
			ZipFile zip = new ZipFile(zipFile);
			for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
				ZipEntry entry = (ZipEntry) entries.nextElement();
				
				String zipEntryName = entry.getName();
				InputStream in = zip.getInputStream(entry);
				String outPath = (targetPath + zipEntryName).replaceAll("\\*", "/");
				// 判断路径是否存在,不存在则创建文件路径
				if (outPath.indexOf('/') > 0) {
					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);
				}
				in.close();
				out.close();
			}
			zip.close();
		} catch (IOException e) {
			log.error("解压缩文件异常:", e);
			return;
		}
	}
	// ------------------------------解压缩文件end----------------------------------------
}

猜你喜欢

转载自blog.csdn.net/u022812849/article/details/50491435