使用java基础类实现zip压缩和zip解压工具类分享
发布时间:2021-11-23 08:03:41
使用java基础类写的一个简单的zip压缩解压工具类
package sun.net.helper;
import java.io.*;
import java.util.logging.Logger;
import java.util.zip.*;
public class ZipUtil {
private final static Logger logger = Logger.getLogger(ZipUtil.class.getName());
private static final int BUFFER = 1024*10;
/**
* 将指定目录压缩到和该目录同名的zip文件,自定义压缩路径
* @param sourceFilePath 目标文件路径
* @param zipFilePath 指定zip文件路径
* @return
*/
public static boolean zip(String sourceFilePath,String zipFilePath){
boolean result=false;
File source=new File(sourceFilePath);
if(!source.exists()){
logger.info(sourceFilePath+" doesn't exist.");
return result;
}
if(!source.isDirectory()){
logger.info(sourceFilePath+" is not a directory.");
return result;
}
File zipFile=new File(zipFilePath+"/"+source.getName()+".zip");
if(zipFile.exists()){
logger.info(zipFile.getName()+" is already exist.");
return result;
}else{
if(!zipFile.getParentFile().exists()){
if(!zipFile.getParentFile().mkdirs()){
logger.info("cann't create file "+zipFile.getName());
return result;
}
}
}
logger.info("creating zip file...");
FileOutputStream dest=null;
ZipOutputStream out =null;
try {
dest = new FileOutputStream(zipFile);
CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
out=new ZipOutputStream(new BufferedOutputStream(checksum));
out.setMethod(ZipOutputStream.DEFLATED);
compress(source,out,source.getName());
result=true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (out != null) {
try {
out.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if(result){
logger.info("done.");
}else{
logger.info("fail.");
}
return result;
}
private static void compress(File file,ZipOutputStream out,String mainFileName) {
if(file.isFile()){
FileInputStream fi= null;
BufferedInputStream origin=null;
try {
fi = new FileInputStream(file);
origin=new BufferedInputStream(fi, BUFFER);
int index=file.getAbsolutePath().indexOf(mainFileName);
String entryName=file.getAbsolutePath().substring(index);
System.out.println(entryName);
ZipEntry entry = new ZipEntry(entryName);
out.putNextEntry(entry);
byte[] data = new byte[BUFFER];
int count;
while((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (origin != null) {
try {
origin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else if (file.isDirectory()){
File[] fs=file.listFiles();
if(fs!=null&&fs.length>0){
for(File f:fs){
compress(f,out,mainFileName);
}
}
}
}
/**
* 将zip文件解压到指定的目录,该zip文件必须是使用该类的zip方法压缩的文件
* @param zipFile
* @param destPath
* @return
*/
public static boolean unzip(File zipFile,String destPath){
boolean result=false;
if(!zipFile.exists()){
logger.info(zipFile.getName()+" doesn't exist.");
return result;
}
File target=new File(destPath);
if(!target.exists()){
if(!target.mkdirs()){
logger.info("cann't create file "+target.getName());
return result;
}
}
String mainFileName=zipFile.getName().replace(".zip","");
File targetFile=new File(destPath+"/"+mainFileName);
if(targetFile.exists()){
logger.info(targetFile.getName()+" already exist.");
return result;
}
ZipInputStream zis =null;
logger.info("start unzip file ...");
try {
FileInputStream fis= new FileInputStream(zipFile);
CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32());
zis = new ZipInputStream(new BufferedInputStream(checksum));
ZipEntry entry;
while((entry = zis.getNextEntry()) != null) {
int count;
byte data[] = new byte[BUFFER];
String entryName=entry.getName();
int index=entryName.indexOf(mainFileName);
String newEntryName=destPath+"/"+entryName.substring(index);
System.out.println(newEntryName);
File temp=new File(newEntryName).getParentFile();
if(!temp.exists()){
if(!temp.mkdirs()){
throw new RuntimeException("create file "+temp.getName() +" fail");
}
}
FileOutputStream fos = new FileOutputStream(newEntryName);
BufferedOutputStream dest = new BufferedOutputStream(fos,BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
}
result=true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (zis != null) {
try {
zis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if(result){
logger.info("done.");
}else{
logger.info("fail.");
}
return result;
}
public static void main(String[] args) throws IOException {
//ZipUtil.zip("D:/apache-tomcat-7.0.30", "d:/temp");
File zipFile=new File("D:/temp/apache-tomcat-7.0.30.zip");
ZipUtil.unzip(zipFile,"d:/temp") ;
}
}
另一个压缩解压示例,二个工具大家参考使用吧
package com.lanp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
/**
* 解压ZIP压缩文件到指定的目录
*/
public final class ZipToFile {
/**
* 缓存区大小默认20480
*/
private final static int FILE_BUFFER_SIZE = 20480;
private ZipToFile() {
}
/**
* 将指定目录的ZIP压缩文件解压到指定的目录
* @param zipFilePath ZIP压缩文件的路径
* @param zipFileName ZIP压缩文件名字
* @param targetFileDir ZIP压缩文件要解压到的目录
* @return flag 布尔返回值
*/
public static boolean unzip(String zipFilePath, String zipFileName, String targetFileDir){
boolean flag = false;
//1.判断压缩文件是否存在,以及里面的内容是否为空
File file = null; //压缩文件(带路径)
ZipFile zipFile = null;
file = new File(zipFilePath + "/" + zipFileName);
System.out.println(">>>>>>解压文件【" + zipFilePath + "/" + zipFileName + "】到【" + targetFileDir + "】目录下<<<<<<");
if(false == file.exists()) {
System.out.println(">>>>>>压缩文件【" + zipFilePath + "/" + zipFileName + "】不存在<<<<<<");
return false;
} else if(0 == file.length()) {
System.out.println(">>>>>>压缩文件【" + zipFilePath + "/" + zipFileName + "】大小为0不需要解压<<<<<<");
return false;
} else {
//2.开始解压ZIP压缩文件的处理
byte[] buf = new byte[FILE_BUFFER_SIZE];
int readSize = -1;
ZipInputStream zis = null;
FileOutputStream fos = null;
try {
// 检查是否是zip文件
zipFile = new ZipFile(file);
zipFile.close();
// 判断目标目录是否存在,不存在则创建
File newdir = new File(targetFileDir);
if (false == newdir.exists()) {
newdir.mkdirs();
newdir = null;
}
zis = new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry = zis.getNextEntry();
// 开始对压缩包内文件进行处理
while (null != zipEntry) {
String zipEntryName = zipEntry.getName().replace('\\', '/');
//判断zipEntry是否为目录,如果是,则创建
if(zipEntry.isDirectory()) {
int indexNumber = zipEntryName.lastIndexOf('/');
File entryDirs = new File(targetFileDir + "/" + zipEntryName.substring(0, indexNumber));
entryDirs.mkdirs();
entryDirs = null;
} else {
try {
fos = new FileOutputStream(targetFileDir + "/" + zipEntryName);
while ((readSize = zis.read(buf, 0, FILE_BUFFER_SIZE)) != -1) {
fos.write(buf, 0, readSize);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getCause());
} finally {
try {
if (null != fos) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
}
}
zipEntry = zis.getNextEntry();
}
flag = true;
} catch (ZipException e) {
e.printStackTrace();
throw new RuntimeException(e.getCause());
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getCause());
} finally {
try {
if (null != zis) {
zis.close();
}
if (null != fos) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
}
}
return flag;
}
/**
* 测试用的Main方法
*/
public static void main(String[] args) {
String zipFilePath = "C:\\home";
String zipFileName = "lp20120301.zip";
String targetFileDir = "C:\\home\\lp20120301";
boolean flag = ZipToFile.unzip(zipFilePath, zipFileName, targetFileDir);
if(flag) {
System.out.println(">>>>>>解压成功<<<<<<");
} else {
System.out.println(">>>>>>解压失败<<<<<<");
}
}
}


猜你喜欢
- 在java的JFrame内通过创建匿名对象的方式做登录界面package com.sxt;import java.awt.Container
- WPF实现一个简单的多运算符表达式计算器,供大家参考,具体内容如下1.先看下效果图首先外围给了一个grid 把他分成了两行 第一行用来显示文
- rpc远程调用可能存在的问题超时的问题。安全的问题。服务与服务之间URL地址管理。在我们的微服务架构通讯,服务之间依赖关系非常大,如果通过传
- 一、需求有时候应用需要在内部切换语言但又不影响系统的语言,比如是应用现在是中文的,系统语言也是中文的,我把应用的切换成英文显示后系统语言还是
- 本文实例讲述了C#使用GZipStream解压缩数据文件的方法。分享给大家供大家参考。具体分析如下:GZipStream用于从一个流读取数据
- Java是如何跳出当前多重循环?不建议使用在最外层前面加一个标记A,然后用break A;可以跳出多重循环因为它不会让你的程序变得更加优雅,
- 一、准备工作1、确定电脑上已经成功安装jdk7.0以上版本2、win10操作系统3、maven安装包 下载地址:http://maven.a
- 本文实例讲述了C#中DataGridView操作技巧。分享给大家供大家参考。具体分析如下:#region 操作DataGridView///
- 前言我们在搭建完集群环境后,不得不考虑的一个问题就是用户访问产生的session如何处理。session的处理有很多种方法,详情见转载的上篇
- 这里写链接内容仿映客送小礼物的特效,顺便复习一下属性动画,话不多说先看效果图。需求分析可以看到整个动画有几部分组成,那我们就把每个部分拆分出
- 今天给大家介绍一下如何用Java swing实现五子棋的开发即用Java开发图形界面程序五子棋,代码由于太多,只贴部分,最下面会附上下载地址
- 目录1、简单介绍2、Lambdas和Scopes3、Lambdas与局部变量4、Lambda体与局部变量5、Lambdas和'Thi
- C# 的析构以及垃圾回收实例分析看书时,自己写的例子代码,了解到几个知识点,记载下来。同时发现自己手写代码的能力比较弱,还是得多写一下。us
- 实例如下所示:public class WebServiceHelper { /// <summary>
- 概述:Flutter 标签类控件大全ChipFlutter内置了多个标签类控件,但本质上它们都是同一个控件,只不过是属性参数不同而已,在学习
- Java 回调函数详解前言:C语言中回调函数解释:回调函数(Callback Function)是怎样一种函数呢?函数是用来被调用的,我们调
- 本文实例为大家分享了JavaWeb实现注册用户名检测的具体代码,供大家参考,具体内容如下案例说明实现一个可以异步获取用户名是否被注册的小案例
- 本文实例为大家分享了C#控制台实现飞行棋小游戏的具体代码,供大家参考,具体内容如下游戏标题static void ShowTitle() &
- 把idea中的项目导入github仓库中步骤详解做完项目进行云端保存是很必要的,我都是存放在github中。所以废活少说直接开始啦。前提是已
- 前言比较运算符用于判断两个数据的大小,例如:大于、等于、不等于。比较的结果是一个布尔值( true 或 false )。Java 中常用的比