java zip打包多级文件夹目录结构(windows)

大概思路:创建总体输出流zipoutputstream,每次找到文件和文件夹都写入一个zipEntity实例,当为文件夹时,则递归方法继续去找里面的文件,当为文件时则处理文件,且是结束递归的条件

    /**
     * 创建zip文件
     *
     * @param source 被打包的文件目录
     * @param zipName 打包后存放的目录及文件名
     * @throws FileNotFoundException
     */
    private void createzipFile(String source, String zipName) {
        File file = new File(source);
        String zipPath="zip文件存放目录";
        try {
            File file1file1 = new File(zipPath);
            if (!file1file1.exists()) {
                file1file1.mkdirs();
            }
            FileOutputStream target = new FileOutputStream(zipName);
            ZipOutputStream out = new ZipOutputStream(target);
            getZipFile(out, file, "");
            out.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
            throw new RuntimeException("创建zip文件失败", e);
        }
    }



/**
     * 将对应文件夹下的文件及文件夹写入对应文件夹目录下
     *
     * @param out
     * @param file
     * @param pareFileName
     */
    private void getZipFile(ZipOutputStream out, File file, String pareFileName) {
        try {
            File files[] = file.listFiles();
            for (File dirFile : files) {
                String temPath = pareFileName;
                if (dirFile.isDirectory()) {
                    pareFileName += dirFile.getName() + File.separator;
                    ZipEntry zipEntry = new ZipEntry(pareFileName);
                    out.putNextEntry(zipEntry);
                    getZipFile(out, dirFile, pareFileName);
                } else {
                    pareFileName += dirFile.getName();
                    FileInputStream fi = new FileInputStream(dirFile);
                    BufferedInputStream origin = new BufferedInputStream(fi);
                    ZipEntry entry = new ZipEntry(pareFileName);
                    out.putNextEntry(entry);
                    int count;
                    while ((count = origin.read()) != -1) {
                        out.write(count);
                    }
                    origin.close();
                }
                pareFileName = temPath;
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new RuntimeException("压缩文件异常", e);
        }
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

焱墩

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

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

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

打赏作者

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

抵扣说明:

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

余额充值