java后端提供循环解压缩zip以及压缩zip工具类/方法.附带一个删除临时文件的方法

一个自用的版本,可以循环解压缩,可以打包一整个文件夹内的所有文件.
全部应用的jdk1.8自带的工具类.欢迎使用.

解压方法:

/**
     * 指定解压单个文件(可循环调用)
     * @param zipFile 解压的文件路径含文件本身
     * @param descDir 解压到某个路径
     * @Author Maiza
     */
    public static void unZipFile(File zipFile,String descDir) {
        File pathFile = new File(descDir);
        OutputStream out = null;
        InputStream in = null;
        ZipFile zip = null;
        try{
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            //设置处理压缩包语言
            zip = new ZipFile(zipFile, Charset.forName("UTF-8"));
            //开始循环解压缩
            for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String zipEntryName = entry.getName();
                in = zip.getInputStream(entry);
                String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
                //判断路径是否存在,不存在则创建文件路径
                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[] buf1 = new byte[1024];
                int len;
                while ((len = in.read(buf1)) > 0) {
                    out.write(buf1, 0, len);
                }
                //每次循环关闭一次流,避免资源泄露.如果不关闭,系统将一直占用资源.
                out.close();
                in.close();
            }
        } catch (Exception e){
            log.error("unZipFile", e);
        } finally {
            try {
                out.close();
                in.close();
                zip.close();
            } catch (Exception e){
                log.error( "finally:" + e.toString());
            }
        }
    }

压缩方法:

/**
     * 压缩文件
     *
     * @param sourceFilePath 源文件路径
     * @param zipFilePath    压缩后文件存储路径
     * @param zipFilename    压缩文件名
     * @Author Maiza
     */
    public static void compressToZip(String sourceFilePath, String zipFilePath, String zipFilename) {
        File sourceFile = new File(sourceFilePath);
        File zipPath = new File(zipFilePath);
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        if (!zipPath.exists()) {
            zipPath.mkdirs();
        }

        File zipFile = new File(zipPath + "/" + zipFilename);
        try {
            fos = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(fos);
            writeZip(sourceFile, "", zos);
            //文件压缩完成后,删除被压缩文件
            boolean flag = deleteDir(sourceFile);
            log.info("删除被压缩文件[" + sourceFile + "]标志:{}", flag);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        } finally {
            try{
                zos.close();
                fos.close();
            } catch (Exception e){
                log.error("compressToZip发生错误:", e);
            }

        }
    }

    /**
     * 遍历所有文件,压缩
     *
     * @param file       源文件目录
     * @param parentPath 压缩文件目录
     * @param zos        文件流
     * @Author Maiza
     */
    private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
        if (file.isDirectory()) {
            //目录
            parentPath += file.getName() + "/";
            File[] files = file.listFiles();
            for (File f : files) {
                writeZip(f, parentPath, zos);
            }
        } else {
            //文件
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                //指定zip文件夹,ZipEntry里的参数决定了压缩文件里的结构
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zos.putNextEntry(zipEntry);
                int len;
                byte[] buffer = new byte[1024 * 10];
                while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
                    zos.write(buffer, 0, len);
                    zos.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage(), e.getCause());
            } finally {
                try {
                    bis.close();
                    fis.close();
                } catch (IOException e) {
                    log.error("writeZip出现错误:", e);
                }
            }
        }
    }

附带一个删除临时解压缩路径内所有文件的方法配合压缩方法使用

/**
     * 删除文件夹
     *
     * @param dir
     * @return
     */
    public static boolean deleteDir (File dir){
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        //删除空文件夹
        return dir.delete();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值