Java实现ZIP解压功能
1.引入依赖
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.9.6</version>
</dependency>
2.Java代码
public class ZipUtils {
private static Logger logger = LoggerFactory.getLogger(ZipUtils.class);
/**
*ZIP文件解压操作类
* @param path 解压的ZIP源文件路径 必须
* @param goalPath 解压的目标文件夹路径 非必须
* @param perFileName 解压文件的文件名前缀 非必须
* @return 返回解压图片和图片路径
* @throws Exception
*/
public static HashMap<String,String> unZip(String path, String goalPath, String perFileName) throws Exception{
int count = -1;
int index = -1;
String savePath = "";
InputStream in = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
String goal_fileName ="";
int bufLength = 1024;
byte[] b = null;
HashMap<String,String> fileNameMap = new HashMap<String, String>();
try {
logger.debug("--解压缩文件:"+path);
ZipFile localFile = new ZipFile(path);
Enumeration<?> entries = localFile.getEntries();
while(entries.hasMoreElements()){
byte[] buf = new byte[bufLength];
ZipEntry tmpEntry = (ZipEntry) entries.nextElement();
String fileName = tmpEntry.getName();
// 得到文件的扩展名
String file_ext_name = fileName.substring(fileName.lastIndexOf(".") + 1);
if(file_ext_name.equals("jpg")||file_ext_name.equals("jpeg")||file_ext_name.equals("png")||file_ext_name.equals("gif")
||file_ext_name.equals("bmp")){
// 设置文件解压缩目标文件夹
if(goalPath!=null&&goalPath.length()!=0){
savePath = goalPath+ "/";
}else{
savePath = path.substring(0, path.lastIndexOf(".")) + "/";
}
File unZipFile = new File(savePath);
if(!unZipFile.exists()){
unZipFile.mkdir();
logger.debug("--解压缩输出目标文件夹不存在,创建目标文件夹"+savePath);
}
// 组装解压的目标文件
if(perFileName!=null&&perFileName.length()!=0){
goal_fileName = perFileName+"_"+fileName;
}else{
goal_fileName = fileName;
}
// 上传的图片格式
fileName = savePath + goal_fileName;
logger.debug("--解压文件:"+fileName);
File file = new File(fileName);
file.createNewFile();
in = localFile.getInputStream(tmpEntry);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos,bufLength);
while((count = in.read(buf))>-1){
bos.write(buf,0,count);
}
fileNameMap.put(goal_fileName,fileName);
bos.flush();
// 关闭资源
closeResource(bos,fos,in);
// 如果是gif格式的图片,则生成临时gif文件,并获取gif图片的第一帧
if (file_ext_name.trim().equals("gif")|| file_ext_name.trim().equals("GIF")) {
logger.debug("####上传的图片格式为:file_ext_name:"+file_ext_name);
// 临时文件夹
String tmpUrl = goalPath + "/gifTmp";
File gifTmpFiles = new File(tmpUrl);
if (!gifTmpFiles.exists()) {
gifTmpFiles.mkdirs();
}
// 临时gif图片
File gifTmpFile = new File(tmpUrl, goal_fileName);
File gifLocalFile = new File(fileName);
FileUtil.copyFile(gifLocalFile, gifTmpFile);
// 获取gif图片的第一帧
try{
b = ImageUtils.returnGifFirstByte(gifTmpFile.getAbsolutePath());
}catch (Exception e){
logger.error("--获取gif图片的第一帧失败",e);
throw new Exception(e);
}
// 删除临时gif图片
logger.debug("####删除GIF文件临时文件:gifTmpFile:"+gifTmpFile.getAbsolutePath());
gifTmpFile.delete();
logger.debug("####删除GIF本地解压文件:gifLocalFile:"+gifLocalFile.getAbsolutePath());
//删除原始本地GIF图片
gifLocalFile.delete();
// 保存原图片
if (b == null || b.length <= 0) {
logger.error("GIF文件为空,解压失败!"+fileName);
throw new Exception("gif fail");
}else{
fileName = fileName.substring(0,fileName.lastIndexOf("."))+".jpg";
logger.debug("####GIF文件转换为本地JPG文件:fileName:"+fileName);
FileOutputStream out = new FileOutputStream(fileName);
out.write(b);
out.close();
}
}
fileNameMap.put(goal_fileName,fileName);
}else{
logger.error("#####文件格式不合法,拒绝解压缩!fileName:"+fileName);
}
}
// 删除解压缩文件
Util.delUrlLocalFile(path);
try {
if(localFile!=null){
localFile.close();
}
} catch (IOException e) {
logger.error("localFile关闭失败!",e);
localFile.close();
}
} catch (Exception e) {
logger.error("zip文件解压失败!",e);
throw new Exception(e);
}
return fileNameMap;
}
public static void closeResource(BufferedOutputStream bos,FileOutputStream fos,InputStream in){
try{
if(bos!=null){
bos.close();
}
}catch(Exception e){
logger.error("BufferedOutputStream关闭失败!",e);
}
try{
if(fos!=null){
fos.close();
}
}catch(Exception e){
logger.error("FileOutputStream关闭失败!",e);
}
try{
if(in!=null){
in.close();
}
}catch(Exception e){
logger.error("inputstream关闭失败!",e);
}
}
}
由于涉及的业务是图片的打包文件,代码仅写了图片文件的解压。
Java实现ZIP解压功能的更多相关文章
- java利用zip解压slpk文件
public static void main(String[] args) { File file = new File("C:\\Users\\Administrator\\Deskto ...
- Linux下安装zip解压功能
liunx服务器上默认没有安装zip命令,所以使用时需安装:apt-get install zip 或 yum install zip linux安装unzip命令:apt-get install ...
- JAVA zip解压 MALFORMED 错误
最近在在使用zip 解压时,使用JDK1.7及以上版本在解压时,某些文件会报异常 Exception in thread "main" java.lang.IllegalArgum ...
- Java zip解压,并遍历zip中的配置文件 .cfg或.properties
1.解析cfg或properties配置文件 讲配置文件,读取,并封装成为map类型数据 /** * 解析cfg文件 * * @param cfgFile * @return */ public st ...
- java压缩文件解压:调用WinRAR5命令强于自己写代码实现
最近,手上维护着一个几年前的系统,技术是用的JSP+Strust2,系统提供了rar和zip两种压缩格式的解压功能,后台是用java实现的 1.解压rar格式,采用的是java-unrar-0.3.j ...
- windows下tomcat zip解压版安装方法
下面记录一下在win7(32位)系统下,安装zip解压版的方法: 一.下载zip压缩包 地址:http://tomcat.apache.org/download-80.cgi 二.解压 我把解压包解压 ...
- linux下 zip解压 tar解压 gz解压 bz2等各种解压文件命令
.tar 解包:tar xvf FileName.tar 打包:tar cvf FileName.tar DirName (注:tar是打包,不是压缩!) ——————————————— .gz 解压 ...
- CentOS7下zip解压和unzip压缩文件
1.安装zip.unzip应用. yum install zip unzip
- MySQL For Windows Zip解压版安装
前言 Windows 下 MySQL 有msi和zip解压安装版两种,而zip版只需解压并做简单配置后就能使用,我个人比较喜欢这种方式. 注意我们这里说的MySQL是指MySQL服务器,有很多初学的同 ...
随机推荐
- 关于mysql字段名和保留字冲突的问题
建了个表,有个字段起名为key,结果insert语句报错了,说是sql不对. 原因:字段key和MySQL的保留字冲突了,当mysql的字段名和保留字冲突的时候,sql语句中的字段名需要加上反引号`` ...
- IntelliJ IDEA java开发 WebService
测试的功能是通过访问solr服务器,获取相关信息,然后以webservice的形式供客户端访问来获取数据.通过查询资料,现在把过程记录如下: 1.环境 IntelliJ IDEA 2017.2.6 J ...
- global constructor
HQ在要求我们修改code style后,又让我检查并去掉"global constructor". 第一次听说这玩意,就研究了一下.发现网上有人讨论的很精彩,就记下来. “glo ...
- (转)Linux下内存映射文件的用法简介
简介: 内存映射文件与虚拟内存有些类似,通过内存映射文件可以保留一个地址空间的区域,同时将物理存储器提交给此区域,只是内存文件映射的物理存储器来自一个已经存在于磁盘上的文件,而非系统的页文件,而且在对 ...
- ActiveMQ订阅模式持久化实现
实现步骤:1.配置发送xml,applicationContext-send.xml <?xml version="1.0" encoding="UTF-8&quo ...
- JCheckBox使用示例
// 初始化 JCheckBox chk=new JCheckBox("XXX"); // 选择 chk.setSelected(true); // 判断选择状态 chk.isSe ...
- 利用HTML5与jQuery技术创建一个简单的自动表单完成
来源:GBin1.com 在线演示 在线下载 谷歌快速搜索自带大量自动完成插件——库中甚至还有一个附带的jQuery UI共享选项.然而今天我要寻找一个替代的解决方案.由DevBridge开发的j ...
- 算法笔记_094:蓝桥杯练习 矩阵相乘(Java)
目录 1 问题描述 2 解决方案 1 问题描述 问题描述 小明最近在为线性代数而头疼,线性代数确实很抽象(也很无聊),可惜他的老师正在讲这矩阵乘法这一段内容. 当然,小明上课打瞌睡也没问题,但线性 ...
- javascript对于0的解读
CreateTime--2017年6月29日10:36:01Author:Marydon javascript对于0的解读 1.0与“0” 1.1 判断0与"0"是否相等 测试 ...
- excel导入sql server 文本被截断,或者一个或多个字符在目标代码页中没有匹配项 错误处理
excel导入sql server 文本被截断,或者一个或多个字符在目标代码页中没有匹配项 错误处理方法: 方案1:修改注册表 出现文本被截断的原因是SQL Server的导入导出为了确定数据表的字段 ...