java文件压缩

116 篇文章 22 订阅

随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)

使用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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

u010142437

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值