java将文件夹压缩成压缩包

1.代码

将文件夹递归达成压缩包,并且支持删除源文件

public class PackageToZIp {

    public static boolean toZip(String source, String destination) {
        try {
            FileOutputStream out = new FileOutputStream(destination);
            ZipOutputStream zipOutputStream = new ZipOutputStream(out);
            File sourceFile = new File(source);
            // 递归压缩文件夹
            compress(sourceFile, zipOutputStream, sourceFile.getName());
            zipOutputStream.flush();
            zipOutputStream.close();
            //不删除源文件 就不用调用这个  要删除就调用
            deleteFile(sourceFile);
        } catch (IOException e) {
            System.out.println("failed to zip compress, exception");
            return false;
        }
        return true;
    }

    public static Boolean deleteFile(File file) {
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()) {
            System.out.println("文件删除失败,请检查文件是否存在以及文件路径是否正确");
            return false;
        }
        //获取目录下子文件
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()) {
                //递归删除目录下的文件
                deleteFile(f);
            } else {
                //文件删除
                f.delete();
            }
        }
        //文件夹删除
        file.delete();
        return true;
    }

    private static void compress(File sourceFile, ZipOutputStream zos, String name) throws IOException {
        byte[] buf = new byte[1024];
        if (sourceFile.isFile()) {
            // 压缩单个文件,压缩后文件名为当前文件名
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 空文件夹的处理(创建一个空ZipEntry)
                zos.putNextEntry(new ZipEntry(name + "/"));
                zos.closeEntry();
            } else {
                // 递归压缩文件夹下的文件
                for (File file : listFiles) {
                    compress(file, zos, name + "/" + file.getName());
                }
            }
        }
    }

    public static void main(String[] args) {
        PackageToZIp.toZip("d:\\Users\\chenkj\\Desktop\\target", "d:\\Users\\chenkj\\Desktop\\demo.zip");
    }

}
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值