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服务器,有很多初学的同 ...
随机推荐
- Python爬虫之一 PySpider 抓取淘宝MM的个人信息和图片
ySpider 是一个非常方便并且功能强大的爬虫框架,支持多线程爬取.JS动态解析,提供了可操作界面.出错重试.定时爬取等等的功能,使用非常人性化. 本篇通过做一个PySpider 项目,来理解 Py ...
- Windows最常用的8个网络CMD命令总结
一,ping 它是用来检查网络是否通畅或者网络连接速度的命令.作为一个生活在网络上的管理员或者黑客来说,ping命令是第一个必须掌握的DOS命令,它所利用的原理是这样的:网络上的机器都有唯一确定的IP ...
- linux经常使用文字处理命令总结
linux grep命令 作用 Linux系统中grep命令是一种强大的文本搜索工具,它能使用正則表達式搜索文本,并把匹 配的行打印出来.grep全称是Global Regular Expressio ...
- 在页面左右一个悬浮div兼容IE6 IE7 8 9 Firefox chrome
在页面左右一个悬浮div兼容IE6 IE7 8 9 Firefox chrome #identifier-pannel { bottom: 345px; margin-left: 512px; pos ...
- 从服务端架构设计角度,深入理解大型APP架构升级
随着智能设备普及和移动互联网发展,移动端应用逐渐成为用户新入口,重要性越来越突出.但企业一般是先有PC端应用,再推APP,APP 1.0版的功能大多从现有PC应用平移过来,没有针对移动自身特点考虑AP ...
- 如何使用angularjs实现表单验证
<!DOCTYPE html> <html ng-app="myApp"> <head> <title>angularjs-vali ...
- 如何使用angularjs实现文本框设置值
<!DOCTYPE html> <html ng-app="myApp"> <head> <title>angularjs-setV ...
- ThinkPHP 3.2 中获取所有函数方法名,以及注释,完整可运行
<?php namespace Home\Controller; use Common\Controller\BaseController; class AuthController exten ...
- 算法笔记_076:蓝桥杯练习 结点选择(Java)
目录 1 问题描述 2 解决方案 1 问题描述 问题描述 有一棵 n 个节点的树,树上每个节点都有一个正整数权值.如果一个点被选择了,那么在树上和它相邻的点都不能被选择.求选出的点的权值和最大是多 ...
- js对数组按顺序排序
console.log("------默认排序(ASCII字符排序)------"); ,,,,]; arr.sort(); //ASCII字符代码从小到大排序 console.l ...