java进行zip压缩

Java实现zip压缩(支持空文件夹)

当文件中含有文件以及文件夹(空文件夹)时同样适用

/**
     * 文件压缩
     *
     * @param src 文件源目录
     * @param des 压缩文件路径
     * @return
     * @author 
     * date 2019-07-26
     **/
    public static void fileZip(String src, String des) {
        File srcPath = new File(src);
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(new File(des)));
            compress(srcPath, out, "");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

对文件进行压缩

private static void compress(File srcPath, ZipOutputStream out, String base) throws Exception {
		//判断是否是目录 取出所有目录下的所有文件
        if (srcPath.isDirectory()) {
            File[] files = srcPath.listFiles();
            out.putNextEntry(new ZipEntry(base + "/"));
            base = base.length() == 0 ? "" : base + "/";
            for (int i = 0; i < files.length; i++) {
                compress(files[i], out, base + files[i].getName());
            }
        } else {
        	//是文件时
            if ("".equals(base)) {
                out.putNextEntry(new ZipEntry(base + "/"));
                base = srcPath.getName();
            }
            out.putNextEntry(new ZipEntry(base));
            FileInputStream in = new FileInputStream(srcPath);
            byte[] data = new byte[4096];
            int b;
            while ((b = in.read(data)) != -1) {
                out.write(data, 0, b);
            }
            in.close();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值