java压缩与解压缩
2019独角兽企业重金招聘Python工程师标准>>>
主要用到apache的ant.jar,也可用jdk的相关类,但会有中文乱码问题。最重要的俩类是ZipFile和ZipEntry,前者将zip文件转为java对象,后者将zip文件中的条目文件转为java对象。 核心代码如下:
压缩代码:
ZipOutputStream zipOs = new ZipOutputStream(fos);
ZipEntry zipEntry = new ZipEntry("entryName");
zipOs.putNextEntry(zipEntry);
解压缩代码:
Enumeration<ZipEntry> entries = zipFile.getEntries();
ZipEntry zipEntry = entries.nextElement();
InputStream ins = zipFile.getInputStream(zipEntry);
需要注意的地方:
针对空文件夹需要特殊处理,需要往Entry中放入"/"+文件夹名+"/"项
zipOs.putNextEntry("/");
详细点的练习: /** * 测试文件压缩与解压缩 * */ public class TestZip {
public static void main(String[] args) {//-->压缩单个文件zipSingleFileOrFolder("D:\\BIZFLOW\\src\\tst\\新建文本文档.zip", "D:\\BIZFLOW\\src\\tst\\新建文本文档.txt");//-->压缩文件夹//zipSingleFileOrFolder("D:\\BIZFLOW\\src\\tst.zip", "D:\\BIZFLOW\\src\\tst");//-->压缩多个文件(不指定压缩文件保存路径)//zipMultiFiles("","D:\\BIZFLOW\\src\\tst\\新建文本文档.txt","D:\\BIZFLOW\\src\\tst\\新建文本文档 - 副本.txt");//-->压缩多个文件(指定压缩文件保存路径)//zipMultiFiles("D:\\BIZFLOW\\src\\tst\\新建.zip","D:\\BIZFLOW\\src\\tst\\新建文本文档.txt","D:\\BIZFLOW\\src\\tst\\新建文本文档 - 副本.txt");//-->解压缩文件//unzipFile("D:\\BIZFLOW\\src\\tst\\新建", "D:\\BIZFLOW\\src\\tst\\新建文本文档.txt等.zip");}/*** 压缩单个文件/文件夹* @param destPath 压缩文件保存路径(为空串/null时默认压缩路径:待压缩文件所在目录,压缩文件名为待压缩文件/文件夹名+“等.zip”)* @param srcPath 待压缩的文件路径*/public static void zipSingleFileOrFolder(String destPath, String srcPath) {if(StringUtils.isBlank(srcPath)) {throw new RuntimeException("待压缩文件夹不可为空!");}if(StringUtils.isNotBlank(destPath) && !destPath.endsWith(".zip")) {throw new RuntimeException("保存文件名应以.zip结尾!");}File file = new File(srcPath);if(!file.exists()) {throw new RuntimeException("路径'"+srcPath+"'下未找到文件");}if(file.isDirectory()) {//压缩文件夹zipFolder(destPath, srcPath);} else {//压缩单个文件zipFile(destPath, srcPath); }}/*** 压缩多个文件* @param destPath 压缩文件保存路径(为空串/null时默认压缩路径:待压缩文件所在目录,压缩文件名为第一个待压缩文件名+“等.zip”)* @param srcPaths 待压缩文件路径集合*/public static void zipMultiFiles(String destPath, String...srcPaths) {if(srcPaths==null || srcPaths.length==0) {throw new RuntimeException("待压缩文件夹不可为空!");}if(StringUtils.isNotBlank(destPath) && !destPath.endsWith(".zip")) {throw new RuntimeException("保存文件名应以.zip结尾!");}zipFiles(destPath, srcPaths);}/*** 解压缩文件* @param destPath 解压缩路径(为空串/null时默认解压缩路径:压缩文件所在目录)* @param zipPath 压缩文件路径*/public static void unzipFile(String destPath, String zipPath) {if(StringUtils.isBlank(zipPath)) {throw new RuntimeException("压缩文件路径不可为空!");}if(!zipPath.endsWith(".zip")) {throw new RuntimeException("保存文件名应以.zip结尾!");}File file = new File(zipPath);if(StringUtils.isBlank(destPath)) {destPath = getUnzipBasePath(file);}if(!file.exists()) {throw new RuntimeException("路径'"+zipPath+"'下未找到文件");}ZipFile zipFile;int len;byte[] buff = new byte[1024];try {zipFile = new ZipFile(zipPath);//获取压缩文件中所有条目Enumeration<ZipEntry> entries = zipFile.getEntries();if(entries!=null) {while(entries.hasMoreElements()) {//压缩文件条目转为文件或文件夹ZipEntry zipEntry = entries.nextElement();//获取输入流InputStream ins = zipFile.getInputStream(zipEntry);BufferedInputStream bis = new BufferedInputStream(ins);File unzipFile = new File(destPath+File.separator+zipEntry.getName());if(zipEntry.isDirectory()) {unzipFile.mkdirs();continue;} File pf = unzipFile.getParentFile();if(pf!=null && !pf.exists()) {pf.mkdirs();}unzipFile.createNewFile();FileOutputStream fos = new FileOutputStream(unzipFile);BufferedOutputStream bos = new BufferedOutputStream(fos);//输出流写文件while((len=bis.read(buff, 0, 1024))!=-1) {bos.write(buff, 0, len);}bos.flush();fos.close();bos.close();}}} catch (IOException e) {e.printStackTrace();throw new RuntimeException();}}/*** 获取解压缩文件基路径* @param zipPath* @return */private static String getUnzipBasePath(File zipPath) {return zipPath.getParentFile().getAbsolutePath();}/*** 压缩单个文件* @param destPath 压缩文件保存路径* @param srcPath 待压缩文件路径*/private static void zipFile(String destPath, String srcPath) {zipFiles(destPath, srcPath);}/*** 压缩多个文件* @param srcPath* @param zipPath*/private static void zipFiles(String destPath, String...srcPaths) {if(StringUtils.isBlank(destPath)) {File srcFile0 = new File(srcPaths[0]);destPath = srcFile0.getParentFile().getAbsolutePath()+File.separator+srcFile0.getName()+"等.zip";}File zipFile = new File(destPath);FileOutputStream fos = null;try {zipFile.createNewFile();zipFile.mkdirs();fos = new FileOutputStream(zipFile);} catch (IOException e) {e.printStackTrace();throw new RuntimeException();}//获取输出流ZipOutputStream zipOs = new ZipOutputStream(fos);//循环将多个文件转为压缩文件条目for(String srcPath : srcPaths) {if(StringUtils.isBlank(srcPath)) {throw new RuntimeException("待压缩文件路径不可为空!");}File srcFile = new File(srcPath);try {ZipEntry zipEntry = new ZipEntry(srcFile.getName());zipOs.putNextEntry(zipEntry);//获取输入流FileInputStream fis = new FileInputStream(srcFile);int len;byte[] buff = new byte[1024];//输入/输出流对拷while((len=fis.read(buff))!=-1) {zipOs.write(buff, 0, len);}fis.close();} catch (FileNotFoundException e) {e.printStackTrace();throw new RuntimeException();} catch (IOException e) {e.printStackTrace();throw new RuntimeException();}}try {zipOs.flush();zipOs.close();} catch (IOException e) {e.printStackTrace();throw new RuntimeException();}}/*** 压缩文件夹* @param destPath 压缩文件保存路径* @param srcPath 待压缩文件夹路径*/private static void zipFolder(String destPath, String srcPath) {File srcFile = new File(srcPath);//如压缩文件保存路径为空,则默认保存路径if(StringUtils.isBlank(destPath)) {destPath = srcFile.getParent()+File.separator+srcFile.getName()+".zip";}FileOutputStream fos = null;ZipOutputStream zipOs = null;try {fos = new FileOutputStream(destPath);zipOs = new ZipOutputStream(fos);//递归往压缩文件中添加文件夹条目zipFolder(srcFile, srcFile, zipOs);zipOs.close();} catch (FileNotFoundException e) {e.printStackTrace();throw new RuntimeException();} catch (IOException e) {e.printStackTrace();throw new RuntimeException();}}/*** 递归往压缩文件中添加文件夹条目* @param srcFile 待压缩文件夹路径* @param baseFile * @param zipOs*/private static void zipFolder(File srcFile, File baseFile, ZipOutputStream zipOs) {int len;byte[] buff = new byte[1024];if(srcFile.isDirectory()) {//针对空文件夹需要特殊处理,需要往Entry中放入"/"+文件夹名+"/"项try {zipOs.putNextEntry(new ZipEntry(srcFile.getAbsolutePath().replaceFirst(baseFile.getParentFile().getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"), "")+"/"));zipOs.closeEntry();} catch (IOException e) {e.printStackTrace();throw new RuntimeException();}//获取当前文件夹下文件列表File[] fileLists = srcFile.listFiles();if(fileLists!=null && fileLists.length>0) {for (int i = 0; i < fileLists.length; i++) {//递归往压缩文件中添加文件夹条目zipFolder(fileLists[i], baseFile, zipOs);}}} else {//文件处理比较简单,直接放入Entrytry {FileInputStream fis = new FileInputStream(srcFile);zipOs.putNextEntry(new ZipEntry(getRelativePath(baseFile.getAbsolutePath(), srcFile)));while((len=fis.read(buff))!=-1) {zipOs.write(buff, 0, len);}zipOs.closeEntry();fis.close();} catch (IOException e) {e.printStackTrace();throw new RuntimeException();}}}/*** 获取相对基路径的相对路径* @param basePath* @param file* @return*/private static String getRelativePath(String basePath, File file) {if(!basePath.equalsIgnoreCase(file.getAbsolutePath())) {return getRelativePath(basePath, file.getParentFile())+File.separator+file.getName();} else {return file.getName();}}}
转载于:https://my.oschina.net/u/213148/blog/177250
java压缩与解压缩相关推荐
- java 压缩、解压缩 tar.gz
引入依赖 <dependency><groupId>org.apache.commons</groupId><artifactId>commons-co ...
- java压缩与解压缩(1)使用java.util.zip
使用这个API没有找到解决中文乱码的问题 import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ...
- java 文件压缩 解压_Java文件压缩与解压缩(一)
package com.cn; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream ...
- java 解压缩 工具类_Java实现的zip压缩及解压缩工具类示例
本文实例讲述了Java实现的zip压缩及解压缩工具类.分享给大家供大家参考,具体如下: import java.io.BufferedInputStream; import java.io.Buffe ...
- java 压缩技术_Java压缩技术(三) ZIP解压缩——Java原生实现
JavaEye的朋友跟我说:"你一口气把ZIP压缩和解压缩都写到一个帖子里,我看起来很累,不如分开好阅读".ok,面向读者需求,我做调整,这里单说ZIP解压缩! 相关链接: Jav ...
- Java 文件压缩与解压缩
Java IO类库中有提供可以压缩与解压缩的类,其中使用最为广泛的是Zip和GZip,使用这两个类可以很方便的压缩数据. 1.使用Gzip进行简单的文件压缩 GZIP接口相对比较简单,如果只要对单个文 ...
- JAVA——GZIP压缩与解压缩
基本概念 GZIP编码:GZIP最早由Jean-loup Gailly和Mark Adler创建,用于UNⅨ系统的文件压缩.我们在Linux中经常会用到后缀为.gz的文件,它们就是GZIP格式的.现今 ...
- Java压缩技术(三) ZIP解压缩——Java原生实现
转载自 Java压缩技术(三) ZIP解压缩--Java原生实现 解压缩与压缩运作方式相反,原理大抵相同,由ZipInputStream通过read方法对数据解压,同时需要通过CheckedInp ...
- java压缩/解压缩zip格式文件
因为项目要用到压缩.解压缩zip格式压缩包,只好自己封装一个,对于网上流行的中文乱码的问题,本文的解决方法是用apache的包代替jdk里的.基本上还是比较好用的. 废话少说,直接上代码. 1 pac ...
最新文章
- Java中的对象和包
- 一次心惊肉跳的服务器误删文件的恢复过程
- pip 安装依赖包 报错 No matching distribution found for pandas
- BOOST 线程完全攻略 - 结束语
- #3771. Triple(生成函数 + 容斥)
- JS向对象中添加和删除属性
- python1乘到10_python写一个循环1+到10打印计算步骤的脚本——纯粹无聊玩的
- 「雕爷学编程」Arduino动手做(21)——激光开关模块
- 在windows7系统中显示和隐藏系统保留盘
- 2021年四川省政府工作报告:促进5G、大数据、区块链等技术与传统产业融合发展
- Graphviz样例之集群流程图
- 大数据分析-时间序列(pandas库 )
- Spark系列-SparkSQL实战
- 从零基础入门Tensorflow2.0 ----九、44.4 签名函数转换成savedmodel
- 装机大师无法发现linux硬盘,进入pe系统找不到硬盘的解决办法
- 【转】推荐几个免费下载破解软件的网站以及系统
- CSS深入理解之absolute
- 羊驼笔记:清算bot
- 日本某地(我猜应该是在米花町)发生了一件谋杀案,警察通过排查确定杀人凶手必为4个嫌疑犯的一个。
- 每日新闻:华为获首个微模块产品PUE测试证书;Linux发布Acumos AI开源架构平台;商汤技联手华侨城中学打造智能实验学校...