千家信息网

JAVA ZIP解压与压缩的操作

发表于:2026-11-04 作者:千家信息网编辑
千家信息网最后更新 2026年11月04日,这篇文章主要介绍"JAVA ZIP解压与压缩的操作",在日常操作中,相信很多人在JAVA ZIP解压与压缩的操作问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"JAVA
千家信息网最后更新 2026年11月04日JAVA ZIP解压与压缩的操作

这篇文章主要介绍"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 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 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解压与压缩的操作"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

文件 结构 文件夹 目录 输出 路径 学习 根目录 结果 内容 名字 实体 对象 方法 更多 处理 帮助 检测 实用 有效 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 科技互联网技术 易互联网科技有限公司 中国 科技 互联网 深圳互联网络科技有限公司 西安互联网科技 互联网科技公司官网 极限挑战互联网科技 上海喔噻互联网科技 济南华为互联网科技产业总部基地 互联网和黑科技的看法 世界互联网科技公司市值排名 南平创想时代互联网科技有限公司 知域互联网科技有限公司大骗子 深圳市优智互联网科技有限公司 内蒙古九一互联网科技 科技信息时代互联网发展 众联互联网络科技 互联网科技对化妆品行业 恒生互联网科技趋势 现代科技的标志之一的互联网 深圳九邦互联网科技有限公司 无线互联网科技 互联网科技英文翻译 互联网科技大奖都有哪些公司 华中科技大学互联网的牛人 互联网公司高科技产品 工业互联网科技成果转化 互联网科技企业商标注意事项 易租星互联网科技有限公司 互联网科技品牌
0