Java 中的 ZipOutputStream 压缩流的使用

参考学习

https://blog.csdn.net/u013087513/article/details/52151227

https://blog.csdn.net/z69183787/article/details/8290811

https://www.cnblogs.com/zeng1994/p/7862288.html

package zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFile {

    public void zip(String filepath,String zippath) throws IOException {
        File fs = new File(filepath);
        ZipOutputStream zo = new ZipOutputStream(new FileOutputStream(zippath));
        zo.setComment("多文件压缩");
        recursionZip(fs,zo,"");
        zo.close();
    }
    private void recursionZip(File fs,ZipOutputStream zo,String baseDir) throws IOException {
        if(fs.isDirectory()) {
            File[] ff = fs.listFiles();
            if(ff.length==0) {
                zo.putNextEntry(new ZipEntry(baseDir + fs.getName()+"/"));
                zo.closeEntry();
            }
            for(File f : ff) {
                recursionZip(f,zo,baseDir + fs.getName() + File.separator);
            }
        }else {
            byte[] b = new byte[1024];
            zo.putNextEntry(new ZipEntry(baseDir + fs.getName()));
            FileInputStream fi = new FileInputStream(fs);
            int len = 0;
            while((len = fi.read(b))!=-1) {
                zo.write(b,0,len);
            }
            fi.close();
            zo.closeEntry();
        }
    }
    public static void main(String[] args) {
        String filepath = "d:"+ File.separator + "hello";
        String zippath = "d:" + File.separator + "hello.zip";
        ZipFile zf = new ZipFile();
        try {
            zf.zip(filepath,zippath);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}

转载于:https://blog.51cto.com/maplebb/2158495

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值