JAVA核心知识点--Zip压缩工具类(二)(解决中文乱码)

在Java项目中需要对文件夹的内容进行Zip压缩,参考了网上的代码并修复了里面的一些问题,例如:中文乱码、目录不存在异常。

所使用的Jar包:ant-*.*.*.jarlog4j-*.*.*.jar,示例工程的CSDN下载地址:

http://download.csdn.net/download/pengjunlee/10043115

ZipUtil工具类源码

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;

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

public class ZipUtil {

	private static final Logger logger = Logger.getLogger(ZipUtil.class);

	/**
	 * 压缩文件或目录
	 * 
	 * @param src
	 *            要压缩的源文件或目录
	 * @param dest
	 *            生成的压缩文件全名,这里是绝对路径
	 * @param encoding
	 *            压缩时采用的编码格式
	 * @throws IOException
	 */
	public static void zip(String src, String dest, String encoding) {
		ZipOutputStream out = null;
		if (isEmptyStr(src) || isEmptyStr(dest)) {
			logger.error("invalid compress parameters...");
			return;
		}
		if (isEmptyStr(encoding)) {
			encoding = "UTF-8";
		}
		try {
			File outFile = new File(dest);

			File parentFile = outFile.getParentFile();
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			out = new ZipOutputStream(outFile);
			out.setEncoding(encoding);
			File fileOrDirectory = new File(src);

			if (fileOrDirectory.isFile()) {
				zipFileOrDirectory(out, fileOrDirectory, "");
			} else {
				File[] entries = fileOrDirectory.listFiles();
				for (int i = 0; i < entries.length; i++) {
					// 递归压缩,更新curPaths
					zipFileOrDirectory(out, entries[i], "");
				}
			}

		} catch (IOException e) {
			logger.error(e.getMessage());
		} finally {
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}
	}

	private static boolean isEmptyStr(String str) {
		return str == null || str.length() == 0;
	}

	/**
	 * 递归压缩文件或目录
	 * 
	 * @param out
	 *            压缩输出流对象
	 * @param file
	 *            要压缩的文件或目录对象
	 * @param curPath
	 *            当前压缩条目的路径,用于指定条目名称的前缀
	 * @throws IOException
	 */
	private static void zipFileOrDirectory(ZipOutputStream out, File file,
			String curPath) {
		FileInputStream in = null;
		try {
			if (!file.isDirectory()) {
				// 压缩文件
				byte[] buffer = new byte[1024 * 1024];
				int len;
				in = new FileInputStream(file);

				ZipEntry entry = new ZipEntry(curPath + file.getName());
				out.putNextEntry(entry);

				while ((len = in.read(buffer)) != -1) {
					out.write(buffer, 0, len);
				}
				out.closeEntry();
			} else {
				// 压缩目录
				File[] entries = file.listFiles();
				for (int i = 0; i < entries.length; i++) {
					// 递归压缩,更新curPath
					zipFileOrDirectory(out, entries[i],
							curPath + file.getName() + "/");
				}
			}
		} catch (IOException e) {
			logger.error(e.getMessage());
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}
	}

	/**
	 * 解压缩
	 * 
	 * @param zipFileName
	 *            源文件
	 * @param outputDirectory
	 *            解压缩后文件存放的目录
	 * @throws IOException
	 */
	@SuppressWarnings({ "rawtypes" })
	public static void unzip(String zipFileName, String outputDirectory,
			String encoding) {

		ZipFile zipFile = null;
		if (isEmptyStr(encoding)) {
			encoding = "UTF-8";
		}
		try {
			zipFile = new ZipFile(zipFileName, encoding);
			Enumeration zipEntries = zipFile.getEntries();
			ZipEntry zipEntry = null;

			File dest = new File(outputDirectory);
			if (!dest.exists()) {
				dest.mkdirs();
			}

			while (zipEntries.hasMoreElements()) {
				zipEntry = (ZipEntry) zipEntries.nextElement();

				String entryName = new String(zipEntry.getName().getBytes(
						encoding), encoding);

				InputStream in = null;
				FileOutputStream out = null;

				try {
					if (zipEntry.isDirectory()) {
						String name = zipEntry.getName();
						name = name.substring(0, name.length() - 1);

						File f = new File(outputDirectory + File.separator
								+ name);
						f.mkdirs();
					} else {
						int index = entryName.lastIndexOf("\\");
						if (index != -1) {
							File df = new File(outputDirectory + File.separator
									+ entryName.substring(0, index));
							df.mkdirs();
						}
						index = entryName.lastIndexOf("/");
						if (index != -1) {
							File df = new File(outputDirectory + File.separator
									+ entryName.substring(0, index));
							df.mkdirs();
						}

						File f = new File(outputDirectory + File.separator
								+ zipEntry.getName());
						// f.createNewFile();
						in = zipFile.getInputStream(zipEntry);
						out = new FileOutputStream(f);

						int len;
						byte[] buffer = new byte[1024 * 1024];

						while ((len = in.read(buffer)) != -1) {
							out.write(buffer, 0, len);
						}
						out.flush();
					}
				} catch (IOException e) {
					logger.error("解压失败...");
					logger.error(e.getMessage());
				} finally {
					if (null != in) {
						try {
							in.close();
						} catch (IOException e) {
							logger.error(e.getMessage());
						}
					}
					if (null != out) {
						try {
							out.close();
						} catch (IOException e) {
							logger.error(e.getMessage());
						}
					}
				}
			}

		} catch (IOException e) {
			logger.error("解压失败...");
			logger.error(e.getMessage());
		} finally {
			if (null != zipFile) {
				try {
					zipFile.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}

	}

	public static void main(String[] args) {
		ZipUtil.zip("D:\\sourceFolder", "D:\\targetFolder\\test.zip", "GBK");
		ZipUtil.unzip("D:\\targetFolder\\test.zip", "D:\\test", "GBK");

	}

}

  

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值