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解压功能的更多相关文章

  1. java利用zip解压slpk文件

    public static void main(String[] args) { File file = new File("C:\\Users\\Administrator\\Deskto ...

  2. Linux下安装zip解压功能

    liunx服务器上默认没有安装zip命令,所以使用时需安装:apt-get install zip 或  yum install zip linux安装unzip命令:apt-get install ...

  3. JAVA zip解压 MALFORMED 错误

    最近在在使用zip 解压时,使用JDK1.7及以上版本在解压时,某些文件会报异常 Exception in thread "main" java.lang.IllegalArgum ...

  4. Java zip解压,并遍历zip中的配置文件 .cfg或.properties

    1.解析cfg或properties配置文件 讲配置文件,读取,并封装成为map类型数据 /** * 解析cfg文件 * * @param cfgFile * @return */ public st ...

  5. java压缩文件解压:调用WinRAR5命令强于自己写代码实现

    最近,手上维护着一个几年前的系统,技术是用的JSP+Strust2,系统提供了rar和zip两种压缩格式的解压功能,后台是用java实现的 1.解压rar格式,采用的是java-unrar-0.3.j ...

  6. windows下tomcat zip解压版安装方法

    下面记录一下在win7(32位)系统下,安装zip解压版的方法: 一.下载zip压缩包 地址:http://tomcat.apache.org/download-80.cgi 二.解压 我把解压包解压 ...

  7. linux下 zip解压 tar解压 gz解压 bz2等各种解压文件命令

    .tar 解包:tar xvf FileName.tar 打包:tar cvf FileName.tar DirName (注:tar是打包,不是压缩!) ——————————————— .gz 解压 ...

  8. CentOS7下zip解压和unzip压缩文件

    1.安装zip.unzip应用. yum install zip unzip

  9. MySQL For Windows Zip解压版安装

    前言 Windows 下 MySQL 有msi和zip解压安装版两种,而zip版只需解压并做简单配置后就能使用,我个人比较喜欢这种方式. 注意我们这里说的MySQL是指MySQL服务器,有很多初学的同 ...

随机推荐

  1. vue项目中使用地图组件

    一.引入高德地图 一般用使用vue-cli webpack最简单粗暴的引入地图api的方法就是,在入口index.html的头部直接引入,记得一定要带上key,如果没有的话去高德地图api的官网申请一 ...

  2. vue项目如何实现剪切板功能--vue-clipboard2

    一.vue项目利用vue-clipboard2实现剪切板的功能 1.安装vue-clipboard2插件:cnpm install --save vue-clipboard2 2.main.js添加 ...

  3. Python 面试中 8 个必考问题(转载)

    Python 面试中 8 个必考问题 1.下面这段代码的输出结果是什么?请解释. def extendList(val, list=[]): list.append(val) return list ...

  4. C#-遍历datatable的几种方法

    遍历datatable的方法2009-- :02方法一: DataTable dt = dataSet.Tables[]; ; i < dt.Rows.Count ; i++) { string ...

  5. Silverlight 安装失败 提示 消息 ID 1603 的解决方法

    消息 ID: 1603 安装过程中出现错误.请执行以下步骤 原因是在以前安装过silverlight,没有安装成功或者没有彻底卸载干净,遗留了一些文件,尤其是安装时突然中断的时候会出现这个问题. 解决 ...

  6. Android_Activity知识点

    一:安卓的目录下面有两个文件夹,一个是assets一个是RES其中在resw文件夹放的所有东西都会在R文件夹中自动对应的生成了一个ID,那么在assets中我们可以放关于这个工程的任何文件. 二:dr ...

  7. super.getclass()的结果是父类还是子类?

    package as; import java.util.Date; public class Test extends Date{ public static void main(String[] ...

  8. java集合Collection接口

    collection集合 Map集合 Hashtable和HashMap的区别: Hashtable的方法是同步的,而HashMap的方法不是.HashMap可以将空值作为一个表的条目的key或val ...

  9. UITableViewCell 添加 checkbox 多选

    TableViewCell多选: CheckBox; - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndex ...

  10. Unity3D研究院之DontDestroyOnLoad的坑

    http://www.xuanyusong.com/archives/2938 Unity中的一个方法DontDestroyOnLoad可以让某些游戏对象在切换场景的时候不是施放,听起来是一个非常好的 ...