温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JAVA ZIP解压与压缩的操作

发布时间:2021-06-22 13:49:59 来源:亿速云 阅读:148 作者:chen 栏目:大数据

这篇文章主要介绍“JAVA ZIP解压与压缩的操作”,在日常操作中,相信很多人在JAVA ZIP解压与压缩的操作问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”JAVA ZIP解压与压缩的操作”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

最近做项目,有地方要用到JAVA的ZIP操作,经过一番折腾,终于通了,特整理了记录一下。闲话少叙,直接上带有注释的代码。

public class ZipUtil {

    private static final Logger logger = Logger.getLogger(ZipUtil.class);

    /**
     * 压缩路径下的所有文件,格式:zip
     *
     * @param path 路径
     * @return 压缩结果
     */
    public static boolean zipPath(String path, String fileName) {
        try {
            File file = new File(path);
            if (!file.isDirectory()) {
                return false;
            }
            File[] files = file.listFiles();
            if (Objects.isNull(files) || files.length < 1) {
                return false;
            }
            List<File> fileList = Arrays.asList(files);
            FileUtil.createDir(Constant.TEMP_PATH);
            FileOutputStream fos = new FileOutputStream(new File(Constant.TEMP_PATH + fileName));
            toZip(fileList, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 压缩文件夹成ZIP
     *
     * @param srcDir           压缩文件夹路径
     * @param out              压缩文件输出流
     * @param keepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(String srcDir, OutputStream out, boolean keepDirStructure) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile, zos, sourceFile.getName(), keepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 压缩文件列表成ZIP
     *
     * @param srcFiles 需要压缩的文件列表
     * @param out      压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                if (srcFile.isDirectory()) {
                    compress(srcFile, zos, srcFile.getName(), true);
                } else {
                    byte[] buf = new byte[Constant.BUFFER_SIZE];
                    zos.putNextEntry(new ZipEntry(srcFile.getName()));
                    int len;
                    FileInputStream in = new FileInputStream(srcFile);
                    while ((len = in.read(buf)) != -1) {
                        zos.write(buf, 0, len);
                    }
                    in.close();
                }
                zos.closeEntry();
            }
            long end = System.currentTimeMillis();
            logger.debug("压缩完成,耗时:" + (end - start) + " ms");
        } catch (Exception e) {
            logger.error("压缩异常");
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 递归压缩方法
     *
     * @param sourceFile       源文件
     * @param zos              zip输出流
     * @param name             压缩后的名称
     * @param keepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean keepDirStructure) throws Exception {
        byte[] buf = new byte[Constant.BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            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);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (keepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (keepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), keepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), keepDirStructure);
                    }

                }
            }
        }
    }

    /**
     * 解压文件到当前路径
     *
     * @param file 待解压文件
     * @return 解压结果
     */
    public static boolean unzipFile(String file, String targetDir) {
        ZipFile zip = null;
        if (!isValidZip(new File(file))) {
            return false;
        }
        try {
            zip = new ZipFile(file, Charset.forName("GBK"));
            if (!FileUtil.createDir(targetDir)) {
                logger.debug("文件夹缺失");
                return false;
            }
            Enumeration<?> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                // 如果是文件夹,就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = targetDir + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                    if (entry.getName().contains("/")) {
                        String path = entry.getName().substring(0, entry.getName().lastIndexOf("/"));
                        if (!FileUtil.createDir(targetDir + path)) {
                            return false;
                        }
                    }
                    String fileName = targetDir + entry.getName().replaceAll("/", Matcher.quoteReplacement(File.separator));
                    System.out.println("文件名:" + fileName);
                    File targetFile = new File(fileName);
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zip.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[Constant.BUFFER_SIZE];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序,先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("解压异常");
            return false;
        } finally {
            if (zip != null) {
                try {
                    zip.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("关闭zip对象异常");
                }
            }
        }
        logger.debug(file + "****解压完毕");
        return true;
    }

    /**
     * 是否为有效的zip文件检测
     *
     * @param file 文件对象
     * @return 检测结果
     */
    public static boolean isValidZip(final File file) {
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(file);
            return true;
        } catch (IOException e) {
            return false;
        } finally {
            try {
                if (zipfile != null) {
                    zipfile.close();
                }
            } catch (IOException e) {
                return false;
            }
        }
    }

到此,关于“JAVA ZIP解压与压缩的操作”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI