JAVA ZIP解压与压缩的操作
发表于:2026-11-05 作者:千家信息网编辑
千家信息网最后更新 2026年11月05日,这篇文章主要介绍"JAVA ZIP解压与压缩的操作",在日常操作中,相信很多人在JAVA ZIP解压与压缩的操作问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"JAVA
千家信息网最后更新 2026年11月05日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安全错误
数据库的锁怎样保障安全
科技股互联网
互联网科技财经
与互联网科技公司
互联网金融公司科技
互联网科技集团
有马互联网科技
北京互联网络科技有限公司
腾讯科技 互联网女皇
科技伦理 互联网公司
青海省互联网新科技
移动互联网科技股
广州新华互联网科技学校电竞方面
互联网科技快讯热点
吉林省码上互联网科技电话
互联网科技平台产品运营
中国科技和美国互联网
广州三三互联网科技有限公司
数字互联网科技有限公司
互联网科技创新方面的资料
广州全民伙伴互联网科技有限公司
广州善班互联网科技
互联网科技股午盘股票涨跌
华中科技有哪些互联网大佬
济南华为互联网科技产业总部基地
智腾互联网科技有限公司
从那以后互联网科技有限公司
互联网公司属于科技吗
西安左小互联网科技有限公司
保山浩联互联网科技有限公司
颐高云石互联网科技