文件的压缩和解压等操作

.1.将文件压缩为zip/rar文件(实质都为zip格式)

/**
     * 创建ZIP文件
     * @param sourcePath 文件或文件夹路径
     * @param zipPath 生成的zip文件存在路径(包括文件名如: 
             E:\\file\\webapps\\ROOT\\resource\\test.zip)
     * @param isDrop 是否删除原文件:true删除、false不删除
    */
    public static void createResZip(String sourcePath, String zipPath) {
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            sourcePath = "E:\\file\\webapps\\ROOT\\resource\\31012227";
            zipPath = "E:\\file\\webapps\\ROOT\\resource\\test.zip";
            fos = new FileOutputStream(zipPath);
            zos = new ZipOutputStream(fos);
            zos.setEncoding("gbk");// 此处修改字节码方式。
            writeZip(new File(sourcePath), "", zos, false);
        } catch (FileNotFoundException e) {
            System.out.println("创建ZIP文件失败");
            e.printStackTrace();
        } finally {
            try {
                if (zos != null) {
                    zos.close();
                }
            } catch (IOException e) {
                System.out.println("创建ZIP文件失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 将文件/文件夹下所有文件转化为输入流输出到zip输出流中
     * @param file
     * @param parentPath
     * @param zos zip输出流
     * @param isDrop 是否删除原文件:true删除、false不删除
     */
    private static void writeZip(File file, String parentPath, ZipOutputStream zos, Boolean isDrop) {
        if (file.exists()) {
            if (file.isDirectory()) {// 处理文件夹
                parentPath += file.getName() + File.separator;
                File[] files = file.listFiles();
                if (files.length != 0) {
                    for (File f : files) {
                        writeZip(f, parentPath, zos, isDrop);
                    }
                } else { //空目录则创建当前目录
                    try {
                        zos.putNextEntry(new ZipEntry(parentPath));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(file);
                    ZipEntry ze = new ZipEntry(parentPath + file.getName());
                    zos.putNextEntry(ze);
                    byte[] content = new byte[1024];
                    int len;
                    while ((len = fis.read(content)) != -1) {
                        zos.write(content, 0, len);
                        zos.flush();
                    }

                } catch (FileNotFoundException e) {
                    System.out.println("创建ZIP文件失败");
                    e.printStackTrace();
                } catch (IOException e) {
                    System.out.println("创建ZIP文件失败");
                    e.printStackTrace();
                } finally {
                    try {
                        if (fis != null) {
                            fis.close();
                        }
                        if (isDrop) {
                            clean(file);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 清空文件和文件目录
     */
    public static void clean(File f) throws Exception {
        String cs[] = f.list();
        if (cs == null || cs.length <= 0) {
            System.out.println("delFile:[ " + f + " ]");
            boolean isDelete = f.delete();
            if (!isDelete) {
                System.out.println("delFile:[ " + f.getName() + "文件删除失败!" + " ]");
                throw new Exception(f.getName() + "文件删除失败!");
            }
        } else {
            for (int i = 0; i < cs.length; i++) {
                String cn = cs[i];
                String cp = f.getPath() + File.separator + cn;
                File f2 = new File(cp);
                if (f2.exists() && f2.isFile()) {
                    System.out.println("delFile:[ " + f2 + " ]");
                    boolean isDelete = f2.delete();
                    if (!isDelete) {
                        System.out.println("delFile:[ " + f2.getName() + "文件删除失败!" + " ]");
                        throw new Exception(f2.getName() + "文件删除失败!");
                    }
                } else if (f2.exists() && f2.isDirectory()) {
                    clean(f2);
                }
            }
            System.out.println("delFile:[ " + f + " ]");
            boolean isDelete = f.delete();
            if (!isDelete) {
                System.out.println("delFile:[ " + f.getName() + "文件删除失败!" + " ]");
                throw new Exception(f.getName() + "文件删除失败!");
            }
        }
    }

2.解压单个文件

/**
    *description:解压文件操作 含多层目录
    *@author: fuxb
    *@date: 2021/7/23 19:15
    @param zipFilePath zip源文件路径 如:E:\webapp\test.zip
     * @param descDir 解压出来的文件保存的文件夹如:E:\webapp\test
    *@return: void
    */
    public static void unZiFiles(String zipFilePath,String descDir){
        File zipFile=new File(zipFilePath);
        File pathFile=new File(descDir);
        if(!pathFile.exists()){
            pathFile.mkdirs();
        }
        ZipFile zip=null;
        InputStream in=null;
        OutputStream out=null;
        try {
            zip=new ZipFile(zipFile);
            Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>)zip.getEntries();
            while(entries.hasMoreElements()){
                ZipEntry entry=(ZipEntry) entries.nextElement();
                String zipEntryName=entry.getName();
                in=zip.getInputStream(entry);
                String outPath=(descDir+"/"+zipEntryName).replace("\\*", "/");
                //推断路径是否存在,不存在则创建文件路径
                File file=new File(outPath.substring(0, outPath.lastIndexOf('/')));
                if(!file.exists()){
                    file.mkdirs();
                }
                //推断文件全路径是否为文件夹,假设是上面已经创建,不须要解压
                if(new File(outPath).isDirectory()){
                    continue;
                }
                out=new FileOutputStream(outPath);
                byte[] buf=new byte[4*1024];
                int len;
                while((len=in.read(buf))>=0){
                    out.write(buf, 0, len);
                }
                in.close();
                System.out.println("==================解压完成==================");
            }
        } catch (Exception e) {
            System.out.println("==================解压失败==================");
            e.printStackTrace();
        }finally{
            try {
                if(zip!=null){
                    zip.close();
                }
                if(in!=null){
                    in.close();
                }
                if(out!=null){
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

3.Java压缩和解压并获取进度

参考文档:Java压缩和解压并获取进度_生而为人我很抱歉-CSDN博客_java 压缩 进度

4.解压加密的zip

参考文档:java zip文件解压(含有密码解压)_Jax_u90b9的博客-CSDN博客_java zip解压 密码

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值