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服务器,有很多初学的同 ...
随机推荐
- C# format 日期 各种 符号 实例分析如何精确C#日期格式到毫秒
摘 自: http://developer.51cto.com/art/200908/141145.htm 实例分析如何精确C#日期格式到毫秒 2009-08-03 10:48 paulfzm jav ...
- [Python爬虫] 之十二:Selenium +phantomjs抓取中的url编码问题
最近在抓取活动树网站 (http://www.huodongshu.com/html/find.html) 上数据时发现,在用搜索框输入中文后,点击搜索,phantomjs抓取数据怎么也抓取不到,但是 ...
- 【Shell】linux中shell变量$#,$@,$0,$1,$2的含义解释 && set 关键字使用
linux中shell变量$#,$@,$0,$1,$2的含义解释 摘抄自:ABS_GUIDE 下载地址:http://www.tldp.org/LDP/abs/abs-guide.pdf linu ...
- Python cx_Oracle问题处理
今天第一次使用Python连接Oracle数据库(多么可怕,三年码农没用Python手动连过Oracle) 首先: pip install cx_Oracle 好,安装完成,测试代码如下: from ...
- Netty利用ChannelGroup广播消息
在Netty中提供了ChannelGroup接口,该接口继承Set接口,因此可以通过ChannelGroup可管理服务器端所有的连接的Channel,然后对所有的连接Channel广播消息. Serv ...
- git使用中的一些问题
ubuntu14.04中从服务器下代码出错如下: yingc@yingc:/media/sf_yingc/work/gitcode/androidtv$ repo sync boxThe authen ...
- DNS message解析
案例吐个槽,命苦啊,要自己动手解包. 另外,这里的内容是半路找来的,如果有冲突,自行翻阅rfc1035.我还没校正过. The Structure 如下图: 所有的DNS message都包含了下面这 ...
- Executor / Executors / ExecutorService /
Java SE5的java.util.concurrent包中的执行器(Executor)将为你管理Thread对象,从而简化了并发编程.Executor在客户端和执行任务之间提供了一个间接层,Exe ...
- javascript 自定义Map
迁移时间:2017年5月25日08:24:19 Author:Marydon 三.自定义Map数据格式 需特别注意的是: js中没有像java中的Map数据格式,js自带的map()方法用于:返回 ...
- vpngate 的使用
第一次为小日本打广告.. .我仅仅想仰天大喊..玛的戈壁. .. 竟然活到这个份上了...想出去看看的往下看.. vpngate 下载: http://pan.baidu.com/s/1hq5x3Ly ...