java实现压缩文件操作

package net.sc.common.util;

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.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import net.sc.spider.exception.SpiderException;

/**
 * @author Aaron
 * @createTime 2014年8月31日 下午10:11:55
 * @desc 实现对压缩文件的操作
 */
public class ZipUtil {

	static final Logger log = LogManager.getLogger(ZipUtil.class);

	/**
	 * @param targetZipFile
	 * @param topDirName
	 *            为压缩文件解压之后,最顶层目录名称
	 * @param sources
	 * @throws SpiderException
	 */
	public void zip(String targetZipFile, String topDirName, String... sources) throws SpiderException {
		log.info("开始创建压缩文件:{}  源文件:{}", targetZipFile);
		File fileZip = new File(targetZipFile);
		if (fileZip.exists()) {
			fileZip.delete();
		}
		File[] sourceFiles = new File[sources.length];
		for (int i = 0; i < sources.length; i++) {
			sourceFiles[i] = new File(sources[i]);
		}
		try {
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(fileZip));
			zip(out, topDirName, sourceFiles);
			out.close();
		} catch (IOException e) {
			log.error(String.format("创建压缩文件:%s 出错", targetZipFile), e);
			throw new SpiderException(SpiderException._ZIP_ERR, "创建压缩文件出错");
		}
		log.info("压缩文件:{} 创建完成", targetZipFile);
	}

	/**
	 * 压缩文件-File
	 * 
	 * @param zipFile
	 *            zip文件
	 * @param srcFiles
	 *            被压缩源文件
	 * @author isea533
	 */
	private void zip(ZipOutputStream out, String path, File... srcFiles) throws SpiderException {
		path = path.replaceAll("\\*", "/");
		if (!StringUtil.isEmpty(path) && !path.endsWith("/")) {
			path += "/";
		}
		byte[] buf = new byte[1024];
		for (int i = 0; i < srcFiles.length; i++) {
			try {
				if (srcFiles[i].isDirectory()) {
					File[] files = srcFiles[i].listFiles();
					String srcPath = srcFiles[i].getName();
					srcPath = srcPath.replaceAll("\\*", "/");
					if (!srcPath.endsWith("/")) {
						srcPath += "/";
					}
					out.putNextEntry(new ZipEntry(path + srcPath));
					zip(out, path + srcPath, files);
				} else {
					FileInputStream in = new FileInputStream(srcFiles[i]);
					log.debug("压缩文件:{}", path + srcFiles[i].getName());
					out.putNextEntry(new ZipEntry(path + srcFiles[i].getName()));
					int len;
					while ((len = in.read(buf)) > 0) {
						out.write(buf, 0, len);
					}
					out.closeEntry();
					in.close();
				}
			} catch (Exception e) {
				log.error(String.format("压缩文件:%s 出错", srcFiles[i].getName()), e);
				throw new SpiderException(SpiderException._ZIP_ERR, "压缩文件出错!");
			}
		}

	}

	public void unzip(String zipPath, String descDir) throws IOException {
		log.info("解压缩文件:{}", zipPath);
		unzip(new File(zipPath), descDir);
		log.info("压缩文件:{} 解压完成", zipPath);
	}

	/**
	 * 解压文件到指定目录
	 * 
	 * @param zipFile
	 * @param descDir
	 * @author isea533
	 */

	public void unzip(File zipFile, String descDir) throws IOException {
		File pathFile = new File(descDir);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
		ZipFile zip = new ZipFile(zipFile);
		for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			String zipEntryName = entry.getName();
			InputStream 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;
			}
			// 输出文件路径信息
			log.debug("解压文件:{}", outPath);

			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();
		}
	}

	public static void main(String args[]) throws Exception {
		ZipUtil zu = new ZipUtil();
		String zipFile = "D:/MyProject/spider-os/web_root/data.zip";
		zu.zip(zipFile, "", "D:/MyProject/spider-os/target/classes/com/", "D:/MyProject/spider-os/target/classes/org/", "D:/MyProject/spider-os/target/classes/net/");
		zu.unzip(zipFile, "D:/MyProject/spider-os/web_root/Test/");

	}
}

 

转载于:https://my.oschina.net/AaronDMC/blog/750766

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值