java 压缩文件

这就不多说废话了,代码注释很清晰,直接可以运行的;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {
        zip("E:\\files\\shopImage\\1234.zip",
                new File("E:\\files\\shopImage\\1234"));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
//1.要压缩的zip文件路径(目标文件)2.被压缩的文件路径(源文件路径)
private static  void zip(String zipFileName, File inputFile) throws Exception {
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
            zipFileName));//创建zip输出流
    BufferedOutputStream bo = new BufferedOutputStream(out);
    zip(out, inputFile, inputFile.getName(), bo);
    bo.close();
    out.close(); // 输出流关闭
    System.out.println("压缩完成");
}

private static void zip(ZipOutputStream out, File f, String base,
                 BufferedOutputStream bo) throws Exception { // 方法重载
    if (f.isDirectory()) {//如果是文件夹的话
        File[] fl = f.listFiles();
        if (fl.length == 0) {//空文件夹压缩
            out.putNextEntry(new ZipEntry(base + "/")); // 创建zip压缩进入点base
            System.out.println(base + "/");
        }
        int k = 0;
        for (int i = 0; i < fl.length; i++) {
            zip(out, fl[i], base + "/" + fl[i].getName(), bo); // 递归遍历子文件夹
        }
        System.out.println("第" + k + "次递归");
        k++;
    } else {//压缩文件
        out.putNextEntry(new ZipEntry(base)); // 创建zip压缩进入点base
        System.out.println(base);
        FileInputStream in = new FileInputStream(f);
        BufferedInputStream bi = new BufferedInputStream(in);
        int b;
        while ((b = bi.read()) != -1) {
            bo.write(b); // 将字节流写入当前zip目录
        }
        bi.close();
        in.close(); // 输入流关闭
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值