java文件压缩功能工具类实现多文件下载、压缩包下载

在项目开发中有选中多个文件打包下载和选中文件夹下载文件夹内所有文件的功能需求。

用到的压缩工具类如下:

public class Compress {
    //压缩包暂存位置
    private static String TEMP_PATH = "D:\\YUN\\DISK\\zipTmp";

    private static Boolean moreFile = Boolean.valueOf(false);

    private static Boolean isFirst = Boolean.valueOf(true);
    //压缩包名字
    private static String zipName = "";

    public Compress(String zipName) {
        this.moreFile = Boolean.valueOf(true);
        this.isFirst = Boolean.valueOf(true);
        this.zipName = zipName;
        this.TEMP_PATH = "D:\\YUN\\DISK\\zipTmp";
    }

    public String compress(List<File> fileList) {
        File zipFile = new File(this.TEMP_PATH + "/"+ zipName + ".zip");
        try {
            //压缩输出流
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
            //遍历文件列表
            for (File file : fileList)
                compress(out, file, null);
            //冲刷缓冲区
            out.flush();
            out.close();
        } catch (IOException e) {
           e.printStackTrace();
        }
        return zipFile.getPath();
    }

    public static void compress(ZipOutputStream out, File input, String name) throws IOException {
        if (name == null)
            name = input.getName();

        //如果是文件夹
        if (input.isDirectory()) {
            //获取子文件列表
            File[] flist = input.listFiles();
            if (flist.length == 0) {
                //如果是空文件夹 压缩一个空文件夹进压缩包
                out.putNextEntry(new ZipEntry(name + "/"));
            }
            //递归调用
            else {
                for (int i = 0; i < flist.length; i++)
                    compress(out, flist[i], name + "/" + flist[i].getName());
            }
        }
        //如果是文件
        else {
            FileInputStream fos = new FileInputStream(input);
            byte[] data = new byte[(int)input.length()];

            fos.read(data);
            out.putNextEntry(new ZipEntry(name));
            out.write(data);

            fos.close();
            out.closeEntry();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值