Java用ZIP格式压缩和解压缩文件
转载:java jdk实例宝典
感觉讲的非常好就转载在这保存!
java.util.zip包实现了Zip格式相关的类库,使用格式zip格式压缩和解压缩文件的时候,须要导入该包。
使用zipoutputstream能够实现文件压缩,全部写入到zipoutputstream输入流中的数据,都会被ZIP格式压缩。
每一个被压缩的文件或者文件夹在zip文件里都相应一个zipentry对象,每一个zipentry都有一个name属性,表示它相对于zip文件文件夹的相对路径,对于文件夹,路径以“/“结尾,对于文件,路劲以文件名称结尾。
zipoutputstream的putnextentry方法往zip文件里加入zipentry,紧接着写入到该文件zipoutputstream流中的数据都被保存到zipentry中,知道调用zipoutputstream的closeentry方法。
zipfile表示一个zip文件,它的entries方法能获得zip文件里的zipentry集合。的奥zipentry的输入流。
实例:
package book.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* 用ZIP压缩和解压缩文件或文件夹
*/
public class CompressUtil {
/**
* 压缩文件或者文件夹
* @param baseDirName 压缩的根文件夹
* @param fileName 根文件夹下待压缩的文件或文件夹名,
* 星号*表示压缩根文件夹下的所有文件。
* @param targetFileName 目标ZIP文件
*/
public static void zipFile(String baseDirName, String fileName,
String targetFileName){
//检測根文件夹是否存在
if (baseDirName == null){
System.out.println("压缩失败,根文件夹不存在:" + baseDirName);
return;
}
File baseDir = new File(baseDirName);
if (!baseDir.exists() || (!baseDir.isDirectory())){
System.out.println("压缩失败,根文件夹不存在:" + baseDirName);
return;
}
String baseDirPath = baseDir.getAbsolutePath();
//目标文件
File targetFile = new File(targetFileName);
try{
//创建一个zip输出流来压缩数据并写入到zip文件
ZipOutputStream out =new ZipOutputStream(
new FileOutputStream(targetFile));
if (fileName.equals("*")){
//将baseDir文件夹下的所有文件压缩到ZIP
CompressUtil.dirToZip(baseDirPath, baseDir, out);
} else {
File file = new File(baseDir, fileName);
if (file.isFile()){
CompressUtil.fileToZip(baseDirPath, file, out);
} else {
CompressUtil.dirToZip(baseDirPath, file, out);
}
}
out.close();
System.out.println("压缩文件成功,目标文件名称:" + targetFileName);
} catch (IOException e){
System.out.println("压缩失败:" + e);
e.printStackTrace();
}
}
/**
* 解压缩ZIP文件,将ZIP文件中的内容解压到targetDIR文件夹下
* @param zipName 待解压缩的ZIP文件名称
* @param targetBaseDirName 目标文件夹
*/
public static void upzipFile(String zipFileName, String targetBaseDirName){
if (!targetBaseDirName.endsWith(File.separator)){
targetBaseDirName += File.separator;
}
try {
//依据ZIP文件创建ZipFile对象
ZipFile zipFile = new ZipFile(zipFileName);
ZipEntry entry = null;
String entryName = null;
String targetFileName = null;
byte[] buffer = new byte[4096];
int bytes_read;
//获取ZIP文件中全部的entry
Enumeration entrys = zipFile.entries();
//遍历全部entry
while (entrys.hasMoreElements()) {
entry = (ZipEntry)entrys.nextElement();
//获得entry的名字
entryName = entry.getName();
targetFileName = targetBaseDirName + entryName;
if (entry.isDirectory()){
// 假设entry是一个文件夹,则创建文件夹
new File(targetFileName).mkdirs();
continue;
} else {
// 假设entry是一个文件,则创建父文件夹
new File(targetFileName).getParentFile().mkdirs();
}
//否则创建文件
File targetFile = new File(targetFileName);
System.out.println("创建文件:" + targetFile.getAbsolutePath());
//打开文件输出流
FileOutputStream os = new FileOutputStream(targetFile);
//从ZipFile对象中打开entry的输入流
InputStream is = zipFile.getInputStream(entry);
while ((bytes_read = is.read(buffer)) != -1){
os.write(buffer, 0, bytes_read);
}
//关闭流
os.close( );
is.close( );
}
System.out.println("解压缩文件成功!");
} catch (IOException err) {
System.err.println("解压缩文件失败: " + err);
}
}
/**
* 将文件夹压缩到ZIP输出流。
*/
private static void dirToZip(String baseDirPath, File dir,
ZipOutputStream out){
if (dir.isDirectory()){
//列出dir文件夹下全部文件
File[] files = dir.listFiles();
// 假设是空文件夹
if (files.length == 0){
ZipEntry entry = new ZipEntry(getEntryName(baseDirPath, dir));
// 存储文件夹信息
try {
out.putNextEntry(entry);
out.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
for (int i=0; i<files.length; i++){
if (files[i].isFile()){
//假设是文件,调用fileToZip方法
CompressUtil.fileToZip(baseDirPath, files[i], out);
} else {
//假设是文件夹,递归调用
CompressUtil.dirToZip(baseDirPath, files[i], out);
}
}
}
}
/**
* 将文件压缩到ZIP输出流
*/
private static void fileToZip(String baseDirPath, File file,
ZipOutputStream out){
FileInputStream in = null;
ZipEntry entry = null;
// 创建复制缓冲区
byte[] buffer = new byte[4096];
int bytes_read;
if (file.isFile()){
try {
// 创建一个文件输入流
in = new FileInputStream(file);
// 做一个ZipEntry
entry = new ZipEntry(getEntryName(baseDirPath, file));
// 存储项信息到压缩文件
out.putNextEntry(entry);
// 复制字节到压缩文件
while((bytes_read = in.read(buffer)) != -1){
out.write(buffer, 0, bytes_read);
}
out.closeEntry();
in.close();
System.out.println("加入文件"
+ file.getAbsolutePath() + "被到ZIP文件里!");
} catch (IOException e){
e.printStackTrace();
}
}
}
/**
* 获取待压缩文件在ZIP文件里entry的名字。即相对于跟文件夹的相对路径名
* @param baseDirPath
* @param file
* @return
*/
private static String getEntryName(String baseDirPath, File file){
if (!baseDirPath.endsWith(File.separator)){
baseDirPath += File.separator;
}
String filePath = file.getAbsolutePath();
// 对于文件夹,必须在entry名字后面加上"/",表示它将以文件夹项存储。
if (file.isDirectory()){
filePath += "/";
}
int index = filePath.indexOf(baseDirPath);
return filePath.substring(index + baseDirPath.length());
}
public static void main(String[] args) {
//压缩C盘下的temp文件夹,压缩后的文件是C:/temp.zip
String baseDirName = "C:/";
String fileName = "temp/";
String zipFileName = "C:/temp.zip";
CompressUtil.zipFile(baseDirName, fileName, zipFileName);
//将刚创建的ZIP文件解压缩到D盘的temp文件夹下
System.out.println();
fileName = "D:/temp";
CompressUtil.upzipFile(zipFileName, fileName);
}
}
Java用ZIP格式压缩和解压缩文件的更多相关文章
- Java对zip格式压缩和解压缩
Java对zip格式压缩和解压缩 通过使用java的相关类可以实现对文件或文件夹的压缩,以及对压缩文件的解压. 1.1 ZIP和GZIP的区别 gzip是一种文件压缩工具(或该压缩工具产生的压缩文件格 ...
- [Java 基础] 使用java.util.zip包压缩和解压缩文件
reference : http://www.open-open.com/lib/view/open1381641653833.html Java API中的import java.util.zip ...
- Java ZIP压缩和解压缩文件(解决中文文件名乱码问题)
Java ZIP压缩和解压缩文件(解决中文文件名乱码问题) 学习了:http://www.tuicool.com/articles/V7BBvy 引用原文: JDK中自带的ZipOutputStrea ...
- Java 的zip压缩和解压缩
Java 的zip压缩和解压缩 好久没有来这写东西了,今天中秋节,有个东西想拿出来分享,一来是工作中遇到的问题,一来是和csdn问候一下,下面就分享一个Java中的zip压缩技术,代码实现比较简单,代 ...
- 使用commons-compress操作zip文件(压缩和解压缩)
http://www.cnblogs.com/luxh/archive/2012/06/28/2568758.html Apache Commons Compress是一个压缩.解压缩文件的类库. 可 ...
- Linux常用命令学习3---(文件的压缩和解压缩命令zip unzip tar、关机和重启命令shutdown reboot……)
1.压缩和解压缩命令 常用压缩格式:.zip..gz..bz2..tar.gz..tar.bz2..rar .zip格式压缩和解压缩命令 zip 压缩文件名 源文件:压缩文件 ...
- IO操作之使用zip包压缩和解压缩文件
转自:http://www.cdtarena.com/java.htmlJava API中的import java.util.zip.*;包下包含了Java对于压缩文件的所有相关操作. 我们可以使 ...
- 【转】Java压缩和解压文件工具类ZipUtil
特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...
- java采用zip方式实现String的压缩和解压缩CompressStringUtil类
CompressStringUtil类:不多说,直接贴代码: /** * 压缩 * * @param paramString * @return */ public static final byte ...
随机推荐
- AFHTTPRequestOperationManager当一个网络请求加入菊花
问: Can you help me to understand, how to use UIActivityIndicatorView+AFNetworking or UIProgressView+ ...
- Demo of Python "Map Reduce Filter"
Here I share with you a demo for python map, reduce and filter functional programming thatowned by m ...
- c++内存泄漏处理(积累)
写c++程序时,常常会出现内存泄漏的问题,这里从网上找了一种非常麻烦的方法:假设想找到每一个cpp文件的内存泄漏,都必须在每一个cpp加上例如以下代码: #include <crtdbg.h&g ...
- Unity 二战中加飞机
一个简短的引论: 谢意: 本申请中使用<Unity3D\2D移动游戏开发>提供资源.著作权属于作者.感谢作者.基于原始时本申请的二次开发. 要素: 1.增加2s cd的机身旋转,旋转时保持 ...
- Solr/SolrCloud -error
状态 2014-08-20 10:46:22,356 INFO [coreZkRegister-1-thread-1] [org.apache.solr.cloud.ShardLeaderElecti ...
- IBatis.net初步使用
最近加班比较忙,时间也比较琐碎,蛮久没有写东西了.这次就总结一下自己使用IBatis.net的一些总结吧. IBatis简介 IBatis.net是一款开源的Orm框架,应该算是从java的IBati ...
- therefore/so/hence/then/accordingly/Thus
这几个词的区别大致可从以下几方面去看:1.therefore adv.因此, 所以=for that reason=consequently常用于连接两个并列分句,其前加“and”或分号“:”.He ...
- 无法Debug SQL: Unable to start T-SQL Debugging. Could not attach to SQL Server process on
今天SSMS debug SQL当脚本,突然错误: Unable to start T-SQL Debugging. Could not attach to SQL Server process on ...
- [WebGL入门]四,渲染准备
注意:文章翻译http://wgld.org/,原作者杉本雅広(doxas),文章中假设有我的额外说明,我会加上[lufy:].另外.鄙人webgl研究还不够深入,一些专业词语,假设翻译有误,欢迎大家 ...
- navicat如何导入sql文件
工具--数据的传输--文件 版权声明:本文博客原创文章,博客,未经同意,不得转载.