java文件压缩

使用java基本的zip库可以进行压缩,但是不支持中文文件名,会出现乱码,这里使用apache tools下的ant.jar可以解决这个问题。

压缩工具类ZipUtil代码:

package com.home;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;

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

public class ZipUtil {
	/**
	 * 提供给外部压缩调用
	 * 
	 * @param src
	 * @param des
	 * @throws IOException
	 */
	public static void zip(String src, String des) throws IOException {
		ZipOutputStream out = null;
		try {
			CheckedOutputStream cos = new CheckedOutputStream(
					new FileOutputStream(des), new Adler32());
			out = new ZipOutputStream(new BufferedOutputStream(cos));
			out.setEncoding("GBK");
			zip(new File(src), out, "");
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * 压缩文件
	 * 
	 * @param file
	 * @param out
	 * @param base
	 * @throws IOException
	 */
	private static void zip(File file, ZipOutputStream out, String base)
			throws IOException {
		if (file.isFile()) {
			if (base.length() > 0) {
				out.putNextEntry(new ZipEntry(base));
			} else {
				out.putNextEntry(new ZipEntry(file.getName()));
			}
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(file), "ISO8859_1"));
			int len;
			while ((len = br.read()) != -1) {
				out.write(len);
			}
			br.close();
		} else if (file.isDirectory()) {
			File[] subFiles = file.listFiles();
			out.putNextEntry(new ZipEntry(base + File.separator));
			base = base.length() != 0 ? base + File.separator : "";
			if (subFiles != null) {
				for (File subFile : subFiles) {
					zip(subFile, out, base + subFile.getName());
				}
			}
		}

	}
}

测试类Test:

package com.home;

public class Test {
	/** 源文件夹路径 */
	private String folderSrcPath = "D://test//测试文件夹";
	/** 压缩后的zip文件存放路劲 */
	private String forderDesPath = "D://test//test1.zip";
	/** 源文件路径 */
	private String fileSrcPath = "D://test//测试.pdf";
	/** 压缩后的zip文件存放路劲 */
	private String fileDesPath = "D://test//test.zip";

	public Test() {
		try {
			ZipUtil.zip(folderSrcPath, forderDesPath);
			ZipUtil.zip(fileSrcPath, fileDesPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new Test();
	}
}

点击下载ant.jar

java文件压缩,布布扣,bubuko.com

java文件压缩

上一篇:Java中Map/List/Set .


下一篇:java返回数组的方法