java zip工具类
依赖jar :apache-ant-1.9.2-bin.zip
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List; import org.apache.commons.lang3.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert; /**
* zip工具
* 用于制作压缩包和解压包
* @author Sun Qinbo
* @version 1.0, 2013-7-26
*/
public class ZipUtils {
private static final Logger log = LoggerFactory.getLogger(ZipUtils.class);
private ZipOutputStream zipOut;
private static byte[] buf = new byte[1024]; /**
* 制作压缩包
*/
public static void zip(OutputStream out, List<FileEntry> fileEntrys, String encoding) {
new ZipUtils(out, fileEntrys, encoding);
} /**
* 制作压缩包
*/
public static void zip(OutputStream out, List<FileEntry> fileEntrys) {
new ZipUtils(out, fileEntrys, null);
} /**
* 根据源目录 制作压缩包
* @param srcFiles 源文件目录
* @param out 输出文件流
* @param filter 文件过滤,不过滤可以为null。
* @param parent 压缩包根目录名,不需要可以为null。
* @param prefix 文件前缀,不需要可以为null。
* @param encoding 编码 ,不设置取系统编码。
*/ public static void zip(File[] srcFiles, OutputStream out, FilenameFilter filter, String parent, String prefix, String encoding) {
Assert.notEmpty(srcFiles);
List<FileEntry> fileEntrys = new ArrayList<FileEntry>();
for (int i = 0; i < srcFiles.length; i++) {
FileEntry fileEntry = new FileEntry(parent, prefix, srcFiles[i], filter);
fileEntrys.add(fileEntry);
}
new ZipUtils(out, fileEntrys, encoding);
} /**
* 创建ZipUtils对象
* @param out 输出流
* @param filter 文件过滤,不过滤可以为null。
* @param fileEntrys 源文件名。可以有多个源文件,如果源文件是目录,那么所有子目录都将被包含。
*/
protected ZipUtils(OutputStream out, List<FileEntry> fileEntrys, String encoding) {
Assert.notEmpty(fileEntrys);
long begin = System.currentTimeMillis();
log.debug("开始制作压缩包");
try {
try {
zipOut = new ZipOutputStream(out);
if (!StringUtils.isBlank(encoding)) {
log.debug("using encoding: {}", encoding);
zipOut.setEncoding(encoding);
} else {
log.debug("using default encoding");
}
for (FileEntry fe : fileEntrys) {
zip(fe.getFile(), fe.getFilter(), fe.getZipEntry(), fe.getPrefix());
}
} finally {
zipOut.close();
}
} catch (IOException e) {
throw new RuntimeException("制作压缩包时,出现IO异常!", e);
}
long end = System.currentTimeMillis();
log.info("制作压缩包成功。耗时:{}ms。", end - begin);
} /**
* 压缩文件
* @param srcFile 源文件
* @param pentry 压缩包根目录名,不需要可以为null。
* @param prefix 文件前缀
* @throws IOException
*/
private void zip(File srcFile, FilenameFilter filter, ZipEntry pentry, String prefix) throws IOException {
ZipEntry entry;
if (srcFile.isDirectory()) {
if (pentry == null) {
entry = new ZipEntry(srcFile.getName());
} else {
entry = new ZipEntry(pentry.getName() + "/" + srcFile.getName());
}
File[] files = srcFile.listFiles(filter);
for (File f : files) {
zip(f, filter, entry, prefix);
}
} else {
if (pentry == null) {
entry = new ZipEntry(prefix + srcFile.getName());
} else {
entry = new ZipEntry(pentry.getName() + "/" + prefix + srcFile.getName());
}
FileInputStream in;
try {
log.debug("读取文件:{}", srcFile.getAbsolutePath());
in = new FileInputStream(srcFile);
try {
zipOut.putNextEntry(entry);
int len;
while ((len = in.read(buf)) > 0) {
zipOut.write(buf, 0, len);
}
zipOut.closeEntry();
} finally {
in.close();
}
} catch (FileNotFoundException e) {
throw new RuntimeException("制作压缩包时,源文件不存在:" + srcFile.getAbsolutePath(), e);
}
}
} /**
* 解压
* @param zipFile 压缩包文件
* @param destDir 压缩路径
* @param encoding
* @author Sun Qinbo
*/
public static void unzip(File zipFile, File destDir, String encoding) {
long begin = System.currentTimeMillis();
log.debug("开始解压缩包");
if (destDir.exists() && !destDir.isDirectory()) {
throw new IllegalArgumentException("destDir is not a directory!");
}
ZipFile zip = null;
InputStream is = null;
FileOutputStream fos = null;
File file;
String name;
int readed;
ZipEntry entry;
try {
try {
if (StringUtils.isNotBlank(encoding)) {
zip = new ZipFile(zipFile, encoding);
} else {
zip = new ZipFile(zipFile);
}
Enumeration<?> en = zip.getEntries();
while (en.hasMoreElements()) {
entry = (ZipEntry) en.nextElement();
name = entry.getName();
name = name.replace('/', File.separatorChar);
file = new File(destDir, name);
if (entry.isDirectory()) {
file.mkdirs();
} else {
// 创建父目录
file.getParentFile().mkdirs();
is = zip.getInputStream(entry);
fos = new FileOutputStream(file);
while ((readed = is.read(buf)) > 0) {
fos.write(buf, 0, readed);
}
fos.close();
is.close();
}
}
} finally {
if (fos != null) {
fos.close();
}
if (is != null) {
is.close();
}
if (zip != null) {
zip.close();
}
}
} catch (IOException e) {
log.error("", e);
}
long end = System.currentTimeMillis();
log.info("解压缩包成功。耗时:{}ms。", end - begin); } /** 测试 */
public static void main(String[] args) throws IOException {
List<FileEntry> fileEntrys = new ArrayList<FileEntry>();
File[] listFiles = new File("d://test").listFiles();
for (int i = 0; i < listFiles.length; i++) {
fileEntrys.add(new FileEntry("", "", listFiles[i]));
}
ZipUtils.zip(new FileOutputStream("D://测试_1.zip"), fileEntrys);
ZipUtils.zip(new File("d://test").listFiles(), new FileOutputStream("D://测试_2.zip"), null, "自定义根目录", "自定义前缀_", "UTF-8");
ZipUtils.unzip(new File("D://测试_2.zip"), new File("D://测试_2"), null);
} /**
* 源文件自定义类型
*/
public static class FileEntry {
private FilenameFilter filter;
private String parent; // 压缩包内的目录名
private File file;
private String prefix; // 压缩文件前缀 public FileEntry(String parent, String prefix, File file, FilenameFilter filter) {
this.parent = parent;
this.prefix = prefix;
this.file = file;
this.filter = filter;
} /**
* @param parent 压缩包内的目录名
* @param file 压缩文件前缀
*/
public FileEntry(String parent, File file) {
this.parent = parent;
this.file = file;
} public FileEntry(String parent, String prefix, File file) {
this(parent, prefix, file, null);
} public ZipEntry getZipEntry() {
if (StringUtils.isBlank(parent)) {
return null;
} else {
return new ZipEntry(parent);
}
} public FilenameFilter getFilter() {
return filter;
} public void setFilter(FilenameFilter filter) {
this.filter = filter;
} public String getParent() {
return parent;
} public void setParent(String parent) {
this.parent = parent;
} public File getFile() {
return file;
} public void setFile(File file) {
this.file = file;
} public String getPrefix() {
if (prefix == null) {
return "";
} else {
return prefix;
}
} public void setPrefix(String prefix) {
this.prefix = prefix;
}
}
}
java zip工具类的更多相关文章
- java zip 工具类
原文:http://www.open-open.com/code/view/1430906539866 package com.topsoft.websites.utils; import java. ...
- java常用工具类(二)
1.FtpUtil package com.itjh.javaUtil; import java.io.File; import java.io.FileOutputStream; import ja ...
- Java Properties工具类详解
1.Java Properties工具类位于java.util.Properties,该工具类的使用极其简单方便.首先该类是继承自 Hashtable<Object,Object> 这就奠 ...
- Java json工具类,jackson工具类,ObjectMapper工具类
Java json工具类,jackson工具类,ObjectMapper工具类 >>>>>>>>>>>>>>> ...
- Java日期工具类,Java时间工具类,Java时间格式化
Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>&g ...
- Java并发工具类 - CountDownLatch
Java并发工具类 - CountDownLatch 1.简介 CountDownLatch是Java1.5之后引入的Java并发工具类,放在java.util.concurrent包下面 http: ...
- MinerUtil.java 爬虫工具类
MinerUtil.java 爬虫工具类 package com.iteye.injavawetrust.miner; import java.io.File; import java.io.File ...
- MinerDB.java 数据库工具类
MinerDB.java 数据库工具类 package com.iteye.injavawetrust.miner; import java.sql.Connection; import java.s ...
- 小记Java时间工具类
小记Java时间工具类 废话不多说,这里主要记录以下几个工具 两个时间只差(Data) 获取时间的格式 格式化时间 返回String 两个时间只差(String) 获取两个时间之间的日期.月份.年份 ...
随机推荐
- Hadoop文件的基本操作
Hadoop提供了大量的API对文件系统中的文件进行操作,主要包括: (1)读取文件 (2)写文件 (3)读取文件属性 (4)列出文件 (5)删除文件 1、读取文件 以下示例中,将hdfs中的一个文件 ...
- 视差滚动(Parallax Scrolling)效果的原理与实现
视差滚动(Parallax Scrolling)效果的原理与实现1.视差滚动效果的主要特点: 1)直观的设计,快速的响应速度,更合适运用于单页面 2)差异滚动 分层视差 页面上很多的 ...
- HTML5简介、视频
HTML5 建立的一些规则: 新特性应该基于 HTML.CSS.DOM 以及 JavaScript. 减少对外部插件的需求(比如 Flash) 更优秀的错误处理 更多取代脚本的标记 HTML5 应该独 ...
- Go and JSON
Go and JSON 在使用Go开发web项目的过程中, 数据库读写操作与JSON格式的输入输出是两块最基础的模块, Go的标准库已经帮我们做了很多, 熟悉database/sql与encoding ...
- UITableView属性和方法
1.初始化一个UITableView - (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style struct CGRect { C ...
- js各种进制数之间的转换
计算机中常用的进制数有二进制.八进制.十进制.十六进制 一.十进制 to 其他 var x = 10; // 或定义其他值均可 x.toString(n); // n 代表要转换到的进制,比如n可以为 ...
- 利用ant进行编译和发布项目
本文通过一个示例来解说如何通过ant进行编译和发布项目.本例按如下目录结构来组织项目. D:/web/antsample项目根目录 D:/web/antsample/src源代码目录 D:/web/a ...
- python学习之路-4 内置函数和装饰器
本篇涉及内容 内置函数 装饰器 内置函数 callable() 判断对象是否可以被调用,返回一个布尔值 1 2 3 4 5 6 7 8 9 10 11 num = 10 print(callabl ...
- 使用SqlCacheDependency依赖项让数据库变化后缓存失效
SqlCacheDependency可以使缓存在数据库或者数据库某张表或者字段变化后让指定缓存失效.对于一些需要及时显示的信息比较有用. 需要.net2.0以后设sql server2005及以后版本 ...
- 多线程下不反复读取SQL Server 表的数据
在进行一些如发送短信.邮件的业务时,我们常常会使用一个表来存储待发送的数据,由后台多个线程不断的从表中读取待发送的数据进行发送.发送完毕后再将数据转移到历史表中,这样保证待发送表的数据普通情况下不会太 ...