java zip压缩和解压(支持中文)

package com.xeon.mis.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;

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

/**
 * 多文件压缩
 * 
 */
public class ZipUtils {
	public static void zipCompress(List<String> srcFiles, String desFile)
			throws Exception {
		FileOutputStream outfile = new FileOutputStream(desFile);
		CheckedOutputStream checkoutput = new CheckedOutputStream(outfile,
				new Adler32());
		BufferedOutputStream out = new BufferedOutputStream(checkoutput);
		ZipOutputStream zos = new ZipOutputStream(out);
		// 乱码解决
		zos.setEncoding("gbk");

		for (String infile : srcFiles) {
			System.out.println("Writing file " + infile);
			BufferedInputStream bin = new BufferedInputStream(
					new FileInputStream(new File(infile)));
			infile = infile.substring(infile.lastIndexOf("\\") + 1);
			zos.putNextEntry(new ZipEntry(infile));
			byte[] c = new byte[1024];
			while ((bin.read(c)) != -1) {
				zos.write(c, 0, c.length);
			}
			bin.close();
			zos.closeEntry();
		}
		zos.close();
		out.close();
		checkoutput.close();
	}

	public static void unzip(String srcFile, String destFile) throws Exception {
		if (!(srcFile != null && srcFile.endsWith(".zip"))) {
			throw new Exception("解压文件必须以.zip结尾");
		}
		ZipFile zipFile = new ZipFile(srcFile, "gbk");
		Enumeration<ZipEntry> entrys = zipFile.getEntries();
		while (entrys.hasMoreElements()) {
			ZipEntry zipEntry = entrys.nextElement();
			String name = zipEntry.getName();
			System.out.println("====" + name);
			// 跳过目录
			if (name.endsWith("/")) {
				continue;
			}
			InputStream in = zipFile.getInputStream(zipEntry);
			BufferedInputStream bufferedinput = new BufferedInputStream(in);
			byte[] b = new byte[1024];
			File file = new File(destFile + name);
			File parent = file.getParentFile();
			if (!parent.exists()) {
				parent.mkdirs();
			}
			BufferedOutputStream bufferedoutput = new BufferedOutputStream(
					new FileOutputStream(file));
			while ((bufferedinput.read(b)) > 0) {
				bufferedoutput.write(b, 0, b.length);
			}
			bufferedoutput.close();
			in.close();
		}
	}

	public static void main(String[] args) throws Exception {
		unzip("j:\\test\\1.zip", "j:\\test\\");

	}
}

java zip压缩和解压(支持中文),古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。