JAVA ZIP解压与压缩的操作
发表于:2025-02-01 作者:千家信息网编辑
千家信息网最后更新 2025年02月01日,这篇文章主要介绍"JAVA ZIP解压与压缩的操作",在日常操作中,相信很多人在JAVA ZIP解压与压缩的操作问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"JAVA
千家信息网最后更新 2025年02月01日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; } ListfileList = 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安全错误
数据库的锁怎样保障安全
济宁hr软件开发公司
计算机与网络安全课后答案
徐汇区无线网络技术供应
互联网教育科技公司名字大全
哪些软件开发外包
国家为什么高度重视网络安全工作
看门狗怎么看服务器
网络安全工程师在哪里找
王者荣耀专区服务器会变吗
天河专业网络安全建设
程序员数据库搭建
网络安全的src
域服务器安全策略
常用的计算机网络安全技术有
ih5远程数据库
湖州营销网络技术怎么样
软件开发自考培训班
数据库连接查询算法
江阴浪潮服务器维修点电话
触手tv服务器和串流码
山东互联网科技公司
数据量大的数据库硬件配置
上海富赢网络技术有限公司
电子签章服务器
服务器机房配置
内蒙古信息网络安全
数据库设计需要哪些图
南方电网的网络安全
sql数据库语言有什么特点
魔兽世界永久60那个服务器人多