Zip操作的工具类
/**
* Copyright 2002-2010 the original author is huanghe.
*/
package com.ucap.web.cm.webapp.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import com.ucap.template.Constants;
import com.ucap.utils.UUIDGenerator;
import com.ucap.utils.formatString.FormatString;
import com.ucap.utils.formatString.Validator;
/**
* 压缩和解压缩工具类
*/
@SuppressWarnings("unchecked")
public class ZipUtil {
private static int bufSize = 4096;
private static byte[] buf = new byte[bufSize];
private static String OS_TYPE;
static {
if (System.getProperty("os.name").equals("Linux")) {
OS_TYPE = "linux";
} else if (System.getProperty("os.name").indexOf("Windows") != -1) {
OS_TYPE = "windows";
}
}
public ZipUtil() {
}
/**
* 压缩文件夹内的文件
*
* @param zipDirectory
* 需要压缩的文件夹名
* @return File 压缩文件对象
*/
public static File doZip(String zipDirectory) {
ZipOutputStream zipOut;
File zipDir = new File(zipDirectory);
String zipFileName = zipDir.getName() + ".zip";// 压缩后生成的zip文件名
if (System.getProperty("os.name").startsWith("Windows")) {
if (!zipDirectory.endsWith("\\"))
zipDirectory = zipDirectory + "\\";
} else {
if (!zipDirectory.endsWith("/"))
zipDirectory = zipDirectory + "/";
}
//判断压缩文件是否已经存在,如果存在则删除
File preZip = new File(zipDirectory + "/" + zipFileName);
if (preZip.exists()) {
try {
FileUtils.forceDelete(preZip);
} catch (IOException e) {
e.printStackTrace();
}
}
//创建临时目录
File tempFolder = createTempFolder();
String tempPath = tempFolder.getAbsolutePath();
File zipFile = new File(tempPath + "/" + zipFileName);
if (!zipFile.getParentFile().exists())
zipFile.getParentFile().mkdirs();
if (zipFile.exists() && zipFile.canWrite())
zipFile.delete();// 如果文件存在就删除原来的文件
try {
zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
handleDir(zipOut, zipDir, "");
zipOut.close();
FileUtils.copyFileToDirectory(zipFile, zipDir);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
//删除临时文件夹
if (tempFolder.exists()) {
try {
FileUtils.deleteDirectory(tempFolder);
} catch (IOException e) {
e.printStackTrace();
}
}
}
File zip = new File(zipDir + "/" + zipFileName);
return zip;
}
/**
* 由doZip调用,递归完成目录文件读取
*
*/
private static void handleDir(ZipOutputStream out, File f, String base) throws IOException {
if (f.isDirectory()) {
File[] fl = f.listFiles();
if (System.getProperty("os.name").startsWith("Windows")) {
base = base.length() == 0 ? "" : base + "\\";
//out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
} else {
base = base.length() == 0 ? "" : base + "/";
//out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
}
for (int i = 0; i < fl.length; i++) {
handleDir(out, fl[i], base + fl[i].getName());
}
} else {
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
FileInputStream in = new FileInputStream(f);
byte b[] = new byte[512];
int len = 0;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
out.closeEntry();
in.close();
}
}
/**
* 解压指定zip文件
*
* @param unZipfileName
* 需要解压的zip文件
* @param destPath
* 目录文件夹,如果目标文件夹为null ,则解压到当前目录下
* @param isDeleteSrc
* 是否删除原压缩文件
* @throws Exception
*/
public static List<String> unZip(File zipfileName, String destPath, boolean isDeleteSrc)
throws Exception {
List<String> ret = new ArrayList<String>();
if (zipfileName == null)
return ret;
if (destPath == null)
destPath = zipfileName.getAbsolutePath().substring(0,
zipfileName.getAbsolutePath().lastIndexOf("\\"))
+ "\\";
FileOutputStream fileOut;
File file;
InputStream inputStream;
ZipFile zipFile;
int readedBytes;
File tempFolder = createTempFolder();
String tempPath = tempFolder.getAbsolutePath();
try {
if (System.getProperty("os.name").equals("Linux"))
zipFile = new org.apache.tools.zip.ZipFile(zipfileName,"GBK");
else
zipFile = new org.apache.tools.zip.ZipFile(zipfileName);
for (Enumeration entries = zipFile.getEntries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (System.getProperty("os.name").equals("Linux"))
entry.setUnixMode(644);//解决linux乱码
file = new File(tempPath + "/" + entry.getName());
if (entry.isDirectory()) {
if (!file.exists())
FileUtils.forceMkdir(file);
} else {
// 如果指定文件的目录不存在,则创建之.
File parent = file.getParentFile();
if (!parent.exists()) {
FileUtils.forceMkdir(parent);
}
ret.add(entry.getName());
inputStream = zipFile.getInputStream(entry);
if (isRequiredSuffix(file.getAbsolutePath(), Constants.REQUIRED_ENCODE_SUFFIXS)) {
String content = IOUtils.toString(inputStream, "UTF-8");
FileUtils.writeStringToFile(file, content, "UTF-8");
} else {
fileOut = new FileOutputStream(file);
while ((readedBytes = inputStream.read(buf)) > 0) {
fileOut.write(buf, 0, readedBytes);
}
fileOut.close();
inputStream.close();
}
}
}
zipFile.close();
File destFolder = new File(destPath);
if (!destFolder.exists()) {
destFolder.mkdir();
}
FileUtils.copyDirectory(tempFolder, destFolder);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
//删除临时文件夹
if (tempFolder.exists()) {
try {
FileUtils.deleteDirectory(tempFolder);
} catch (IOException e) {
e.printStackTrace();
}
}
//删除上传的压缩文件
if (isDeleteSrc)
zipfileName.delete();
}
return ret;
}
private static File createTempFolder() {
File tempFolder = null;
String tempPath = "";
try{
String tempFileName = UUIDGenerator.generate();
if (OS_TYPE.equals("window"))
tempPath = "C:/" + tempFileName;
else
tempPath = "/tmp/" + tempFileName;
tempFolder = new File(tempPath);
if (!tempFolder.exists()) {
tempFolder.mkdir();
}
}catch (Exception e) {
System.out.println("CreateTempFolder:"+tempPath +" Exception:" + e.getMessage());
}
return tempFolder;
}
// 设置缓冲区大小
public void setBufSize(int bufSize) {
this.bufSize = bufSize;
}
// 测试AntZip类
public static void main(String[] args) throws Exception {
ZipUtil m_zip = new ZipUtil();
String filepath = "C:\\template\\template_upload/site/";
try {
m_zip.doZip(filepath);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 判断文件的后缀名是否包含在是否以suffixs中
* @param fileName
* @param suffixs
* @return
*/
public static boolean isRequiredSuffix(String fileName, String... suffixs) {
if (Validator.isEmpty(fileName)) {
return false;
}
if (suffixs == null || suffixs.length < 1) {
return false;
}
for (String str : suffixs) {
if (fileName.indexOf("." + str) == fileName.length() - ("." + str).length()) {
return true;
}
}
return false;
}
/**
* 判断解压的文件是否包含汉字。
*
* @param zipfileName 要解压的文件
* @return 返回判断结果,true 含有 ;false 不含有
*/
public static boolean isHaveChinese(File zipfileName) {
ZipFile zipFile = null;
try {
zipFile = new ZipFile(zipfileName);
ZipEntry zipEntry = null;
Enumeration e = zipFile.getEntries();
while (e.hasMoreElements()) {
zipEntry = (ZipEntry) e.nextElement();
if (FormatString.IsHaveChinese(zipEntry.getName())) {
return true;
}
}
return false;
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
}
Zip操作的工具类的更多相关文章
- 自己封装的poi操作Excel工具类
自己封装的poi操作Excel工具类 在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完 ...
- Redis操作Set工具类封装,Java Redis Set命令封装
Redis操作Set工具类封装,Java Redis Set命令封装 >>>>>>>>>>>>>>>>& ...
- Redis操作List工具类封装,Java Redis List命令封装
Redis操作List工具类封装,Java Redis List命令封装 >>>>>>>>>>>>>>>> ...
- Redis操作Hash工具类封装,Redis工具类封装
Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...
- Redis操作字符串工具类封装,Redis工具类封装
Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...
- java中文件操作的工具类
代码: package com.lky.pojo; import java.io.BufferedReader; import java.io.BufferedWriter; import java. ...
- Java操作Redis工具类
依赖 jar 包 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis< ...
- 使用JDK的zip编写打包工具类
JDK自带的zip AIP在java.util.zip包下面,主要有以下几个类: java.util.zip.ZipEntryjava.util.zip.ZipInputStreamjava.util ...
- android操作ini工具类
package com.smarteye.common; import java.io.BufferedReader; import java.io.BufferedWriter; import ja ...
随机推荐
- ROS探索总结(十八)——重读tf
在之前的博客中,有讲解tf的相关内容,本篇博客重新整理了tf的介绍和学习内容,对tf的认识会更加系统. 1 tf简介 1.1 什么是tf tf是一个让用户随时间跟踪多个参考系的功能包,它使用一种树型数 ...
- Android自定义ViewGroup(四、打造自己的布局容器)
转载请标明出处: http://blog.csdn.net/xmxkf/article/details/51500304 本文出自:[openXu的博客] 目录: 简单实现水平排列效果 自定义Layo ...
- Struts 2 之拦截器
拦截器概述 Struts2拦截器是在访问某个Action或Action的某个方法,字段之前或之后实施拦截,并且Struts2拦截器是可插拔的,拦截器是AOP(Aspect Oriented Progr ...
- Dynamics CRM 通过PowerShell启用AllowDeclarativeWorkflows即自定义XAML WorkFlows
CRM的工作流即workflow,不了解的人乍听之下以为是审批流,其实不是的,CRM本身是不带审批功能的,要实现审批必须要第三方的工作流引擎的配合,当然你也可以自己开发. 工作流刚开始出现的时候只有异 ...
- Cocos2D在新版Swift中常量枚举值引用代码的修改
大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 我们知道在SpriteBuilder中是无法直接给一个CCB文 ...
- 插件占坑,四大组件动态注册前奏(一) 系统Activity的启动流程
转载请注明出处:http://blog.csdn.net/hejjunlin/article/details/52190050 前言:为什么要了解系统Activity,Service,,BroadCa ...
- iOS中 最新微信支付/最全的微信支付教程详解 韩俊强的博客
每日更新关注:http://weibo.com/hanjunqiang 新浪微博! 亲们, 首先让我们来看一下微信支付的流程吧. 1. 注册微信开放平台,创建应用获取appid,appSecret, ...
- Eclipse中如何快速查看jar包中 的class源码
我们查看jar源码时,一般是安装个jd-gui,把jar拷出来,然后从jd-gui中打开jar再查看源码,这个过程不免有些麻烦,当然,本篇所讲的快速查看的方法也没什么高科技手段,只是将jd-gui集成 ...
- XMPP即时通讯资料记录
几天开始研究XMPP即时通讯的技术,来实现移动应用的计时聊天功能.记录下参考的博客地址,还挺详细的. http://blog.csdn.net/fhbystudy/article/details/16 ...
- 学习TensorFlow,邂逅MNIST数据集
如果说"Hello Word!"是程序员的第一个程序,那么MNIST数据集,毫无疑问是机器学习者第一个训练的数据集,本文将使用Google公布的TensorFLow来学习训练MNI ...