使用JDK的zip编写打包工具类
JDK自带的zip AIP在java.util.zip包下面,主要有以下几个类:
java.util.zip.ZipEntry
java.util.zip.ZipInputStream
java.util.zip.ZipOutputStream
本文编写的zip工具类有以下功能:打包(单个文件、目录)、解包、查看zip包文件
工具类代码如下
package org.net5ijy.util.zip; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream; /**
* ZIP工具类
*
*/
public class ZipUtil { /**
* 解包时的读写大小:10MB
*/
private static final int SIZE = 1024 * 1024 * 10; /**
* 打包
*
* @param src
* - 需要打包的文件或目录,不可以是根目录,为根目录时抛出IOException
* @param zipFile
* - 打包后的.zip文件
* @throws IOException
*/
public static void zip(File src, File zipFile) throws IOException { // 不可以压缩根目录
if (src.getParent() == null) {
throw new IOException("不可以压缩根目录");
}
// 获取基目录
String base = src.getParentFile().getAbsolutePath(); ZipOutputStream out = null;
BufferedOutputStream bos = null; try { out = new ZipOutputStream(new FileOutputStream(zipFile)); // 创建缓冲输出流
bos = new BufferedOutputStream(out); // 调用函数
zip(out, bos, src, base); } catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
// 关闭流
if (bos != null) {
bos.close();
}
if (out != null) {
out.close();
}
}
} private static void zip(ZipOutputStream out, BufferedOutputStream bos,
File sourceFile, String base) throws IOException { // 如果路径为目录(文件夹)
if (sourceFile.isDirectory()) {
out.putNextEntry(new ZipEntry(sourceFile.getAbsolutePath().replace(
base + File.separator, "")
+ "/"));
// 取出文件夹中的文件(或子文件夹)
File[] flist = sourceFile.listFiles();
if (flist.length > 0) {
for (int i = 0; i < flist.length; i++) {
zip(out, bos, flist[i], base);
}
}
} else {// 如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
out.putNextEntry(new ZipEntry(sourceFile.getAbsolutePath().replace(
base + File.separator, "")));
BufferedInputStream bis = null;
try {
// 文件输入流
bis = new BufferedInputStream(new FileInputStream(sourceFile));
int b = bis.read();
// 将源文件写入到zip文件中
while (b > -1) {
bos.write(b);
b = bis.read();
}
bos.flush();
} catch (Exception e) {
throw e;
} finally {
if (bis != null) {
bis.close();
}
}
}
} /**
* 解包
*
* @param zipFile
* - 需要解包的.zip文件
* @param targetFolder
* - 目标目录
* @throws IOException
*/
public static void unzip(File zipFile, File targetFolder)
throws IOException { // 如果源文件是null 或者 不是一个文件
if (zipFile == null || !zipFile.isFile()
|| !zipFile.getName().endsWith(".zip")) {
throw new IOException("请选择正确的.zip文件");
} // 如果目标目录为null 或者 不是一个目录
if (targetFolder == null || !targetFolder.isDirectory()) {
throw new IOException("请选择正确的解压目录");
} // 定义zip文件输入流
ZipInputStream zin = null; try { // 从zipFile创建对应的ZipInputStream输入流
zin = new ZipInputStream(new FileInputStream(zipFile)); // 获取下一个条目
for (ZipEntry entry = zin.getNextEntry(); entry != null; entry = zin
.getNextEntry()) { // 获取文件或者目录名
String name = entry.getName();
// 目录
if (name.endsWith("/")) {
File dir = new File(targetFolder, name);
dir.mkdirs();
} else {// 文件
unzip(targetFolder, zin, name);
}
}
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
if (zin != null) {
zin.close();
}
}
} private static void unzip(File targetFolder, ZipInputStream zin, String name)
throws IOException { // 定义输出流
FileOutputStream out = null; try { // 创建输出流
out = new FileOutputStream(new File(targetFolder.getAbsolutePath()
+ File.separator + name)); byte[] buf = new byte[SIZE];
int len = zin.read(buf); while (len > -1) {
out.write(buf, 0, len);
len = zin.read(buf);
}
out.flush(); } catch (Exception e) {
throw e;
} finally {
if (out != null) {
out.close();
}
}
} /**
* 获取.zip文件中的条目集合
*
* @param zipFile
* - 待查看的.zip文件
* @return 条目的集合
* @throws IOException
*/
public static List<ZipEntry> zipEntryList(File zipFile) throws IOException { // 如果源文件是null 或者 不是一个文件
if (zipFile == null || !zipFile.isFile()) {
throw new IOException("请选择正确的.zip文件");
} // 定义zip文件输入流
ZipInputStream zin = null; List<ZipEntry> l = new ArrayList<ZipEntry>(); try {
// 从zipFile创建对应的ZipInputStream输入流
zin = new ZipInputStream(new FileInputStream(zipFile));
// 获取下一个条目
ZipEntry entry = zin.getNextEntry(); while (entry != null) {
l.add(entry);
entry = zin.getNextEntry();
}
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
if (zin != null) {
zin.close();
}
}
return l;
} /**
* 获取.zip文件中的条目名称集合
*
* @param zipFile
* - 待查看的.zip文件
* @return 条目名称集合
* @throws IOException
*/
public static List<String> zipEntryNameList(File zipFile)
throws IOException {
List<String> l = new ArrayList<String>();
List<ZipEntry> entryList = zipEntryList(zipFile);
for (ZipEntry zipEntry : entryList) {
l.add(zipEntry.getName());
}
return l;
}
}
测试代码
import static org.net5ijy.util.zip.ZipUtil.*; public class ZipUtilTest { public static void main(String[] args) throws IOException { zip(new File(
"D:\\workspace\\SpringCloud\\zip-demo\\src\\org\\net5ijy\\util\\zip\\ZipUtil.java"),
new File("d:\\zip01.zip")); zip(new File("D:\\workspace\\SpringCloud\\spring-data-demo2\\"),
new File("d:\\zip02.zip")); unzip(new File("d:\\zip02.zip"), new File("D:\\a\\")); List<String> nameList = zipEntryNameList(new File("d:\\zip02.zip"));
for (String name : nameList) {
System.out.println(name);
}
}
}
使用JDK的zip编写打包工具类的更多相关文章
- 【SSH三大框架】Hibernate基础第二篇:编写HibernateUtil工具类优化性能
相对于上一篇中的代码编写HibernateUtil类以提高程序的执行速度 首先,仍然要写一个javabean(User.java): package cn.itcast.hibernate.domai ...
- AntZipUtils【基于Ant的Zip压缩解压缩工具类】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 Android 压缩解压zip文件一般分为两种方式: 基于JDK的Zip压缩工具类 该版本存在问题:压缩时如果目录或文件名含有中文, ...
- JSR303完成validate校验并编写BeanValidator工具类
一.引入pom依赖 <!-- validator --> <dependency> <groupId>javax.validation</groupId> ...
- JDK在线API及常用工具类
API http://tool.oschina.net/apidocs/apidoc?api=jdk-zh Java SE常用工具类 java.util.Arrays java.util.Collec ...
- java jdk原生的http请求工具类
package com.base; import java.io.IOException; import java.io.InputStream; import java.io.InputStream ...
- Zip操作的工具类
/** * Copyright 2002-2010 the original author is huanghe. */package com.ucap.web.cm.webapp.util; ...
- JDBC_part2_DML以及预编译_编写DBUtil工具类
本文为博主辛苦总结,希望自己以后返回来看的时候理解更深刻,也希望可以起到帮助初学者的作用. 转载请注明 出自 : luogg的博客园 谢谢配合! jdbc day02 DML语法 比起插叙语句,没有R ...
- 观察者模式学习--使用jdk的工具类简单实现
观察者模式学习之二:使用jdk的自带的工具类实现,与自己实现相比,两者有以下的区别: 1,自己实现,需要定义观察者的接口类和目标对象的接口类.使用java util的工具类,则不需要自己定义观察者和目 ...
- Java操作zip压缩和解压缩文件工具类
需要用到ant.jar(这里使用的是ant-1.6.5.jar) import java.io.File; import java.io.FileInputStream; import java.io ...
随机推荐
- [原创]STAR法则
[原创]STAR法则 STAR法则是情境(situation).任务(task).行动(action).结果(result)四项的缩写. STAR法则是一种常常被面试官使用的工具,用来收集面试者与工作 ...
- GuavaCache简介(一)是轻量级的框架 少量数据,并且 过期时间相同 可以用 GuavaCache
还有一篇文章是讲解redis 如何删除过期数据的,参考:Redis的内存回收策略和内存上限(阿里) 划重点:在GuavaCache中,并不存在任何线程!它实现机制是在写操作时顺带做少量的维护工作(如清 ...
- dubbo源码分析之过滤器Filter-12
https://blog.csdn.net/luoyang_java/article/details/86682668 Dubbo 是阿里巴巴开源的一个高性能优秀的服务框架,使得应用可通过高性能的 R ...
- Nginx配置proxy_pass转发/路径问题
proxy_ignore_client_abort on; #不允许代理端主动关闭连接 upstream的负载均衡,四种调度算法 #调度算法1:轮询.每个请求按时间顺序逐一分配到不同的后端服务器,如果 ...
- Better ultra_simple for Slamtec RPLIDAR on Linux
Improved the ultra_simple program to visualize the samples with GLUT on Linux, tested with Slamtec R ...
- python 使用 elasticsearch 常用方法(聚合)
#记录聚合查询方法 from elasticsearch import Elasticsearch es = Elasticsearch(['xx.xx.xx.xx:9200']) #获取最小的年龄r ...
- python时间戳,获取当前时间,时间格式转换,求出前几天或后几天的时间
import time import datetime import locale import random class TimeUtil: def __init__(self, curtime=N ...
- springboot 读取配置文件
读取配置文件 在以前的项目中我们主要在 XML 文件中进行框架配置,业务的相关配置会放在属性文件中,然后通过一个属性读取的工具类来读取配置信息. 在 Spring Boot 中我们不再需要使用这种方式 ...
- EasyDSS高性能RTMP、HLS(m3u8)、HTTP-FLV、RTSP流媒体服务器启用https服务申请免费证书
背景分析 目前想在 web 上使用 HTTPS 的话, 你需要获得一个证书文件, 该证书由一个受浏览器信任的公司所签署. 一旦你获得了它, 你就在你的 web 服务器上指定其所在的位置, 以及与你关联 ...
- ABP .NETCore更新数据库时一直连接的之前数据库
使用Update-Database -Verbose更新数据库时,在appsettings.json配置文件中已修改为新的连接字符串,但是使用命令更新数据库时仍然连接的是之前的数据库. 后来把代码移至 ...