使用Java对文件进行解压缩
最近在一个项目中需要对文件进行自动的解压缩,Java提供了这种支持,还是挺好用的。
工具包封装在java.util.zip中。
1.首先是多个文件压缩成一个ZIP文件
思路:用一个ZipOutputStream包装一个目的ZIP文件--->遍历文件数组:对每一个文件创建一个ZipEntry并put进ZipOutputStream中。读取当前文件的数据流写入ZipOutputStream中。
代码实现:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; /**
*多文件压缩
*@author wxisme
*@time 2015-9-24 下午5:13:32
*/ public final class FilesToZip { private FilesToZip(){} /**
* 压缩多个文件到一个zip文件中
* @param files 待压缩文件数组
* @param zipFilePath 压缩后的zip文件路径
* @param fileName zip文件的名字
* @return 是否成功
*/
public static boolean fileToZip(File[] files,String zipFilePath,String fileName){
boolean flag = false;
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null; try {
File zipFile = new File(zipFilePath + "/" + fileName +".zip");
if(zipFile.exists()) {
zipFile.delete();
}
File[] sourceFiles = files;
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
byte[] bufs = new byte[1024*10];
for(int i=0;i<sourceFiles.length;i++){
//创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
zos.putNextEntry(zipEntry);
//读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFiles[i]);
bis = new BufferedInputStream(fis, 1024*10);
int read = 0;
while((read=bis.read(bufs, 0, 1024*10)) != -1){
zos.write(bufs,0,read);
}
}
flag = true; } catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally{
//关闭流
try {
if(null != bis) bis.close();
if(null != zos) zos.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
} return flag;
} }
2.对包含有文件夹的文件数组进行压缩
思路:遍历文件数组,判断是否是文件。如果是文件步骤同1,如果是文件夹(目录)则递归压缩这个文件夹。其他步骤和1类似。
代码实现:
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.ZipOutputStream; /**
*多文件夹压缩
*@author wxisme
*@time 2015-9-24 下午7:36:06
*/
public final class MultiZip { public static void ZipFiles(ZipOutputStream out,String path,File... srcFiles) {
path = path.replaceAll("\\*", "/");
if(!path.endsWith("/")){
path+="/";
}
byte[] buf = new byte[1024];
try {
for(int i=0;i<srcFiles.length;i++){
if(srcFiles[i].getName().endsWith(".zip")) {
//防止形成死循环
continue;
}
if(srcFiles[i].isDirectory()){
File[] files = srcFiles[i].listFiles();
String srcPath = srcFiles[i].getName();
srcPath = srcPath.replaceAll("\\*", "/");
if(!srcPath.endsWith("/")){
srcPath+="/";
}
out.putNextEntry(new ZipEntry(path+srcPath));
ZipFiles(out,path+srcPath,files);
}
else{
FileInputStream in = new FileInputStream(srcFiles[i]);
System.out.println(path + srcFiles[i].getName());
out.putNextEntry(new ZipEntry(path + srcFiles[i].getName()));
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.closeEntry();
in.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
} public static void ZipFiles(File zip,String path,File... srcFiles) throws IOException {
if(zip.exists()) {
zip.delete();
}
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zip));
ZipFiles(out,path,srcFiles);
out.close();
} }
3.解压
思路:获取压缩文件的ZipEntry,对每个ZipEntry进行恢复操作。创建同名文件获取数据流写入文件。
代码实现:
package com.wxisme.demo; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; /**
*解压文件
*@author wxisme
*@time 2015-10-5 下午9:18:57
*/
public class Decompression { /**
* 解压
* @param zipFilePath 待解压文件的路径
* @param unzipFilePath 解压后的文件存储路径
* @throws Exception
*/
public static void unzip(String zipFilePath, String unzipFilePath) throws Exception {
File zipFile = new File(zipFilePath); //创建解压缩文件保存的路径
File unzipFileDir = new File(unzipFilePath);
if (!unzipFileDir.exists() || !unzipFileDir.isDirectory()) {
unzipFileDir.mkdirs();
} //开始解压
ZipEntry entry = null;
String entryFilePath = null, entryDirPath = null;
File entryFile = null, entryDir = null;
int index = 0, count = 0;
byte[] buffer = new byte[1024];
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
ZipFile zip = new ZipFile(zipFile);
Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>)zip.entries();
//循环对压缩包里的每一个文件进行解压
while(entries.hasMoreElements()) {
entry = entries.nextElement();
//构建压缩包中一个文件解压后保存的文件全路径
entryFilePath = unzipFilePath + File.separator + entry.getName();
//构建解压后保存的文件夹路径
index = entryFilePath.lastIndexOf(File.separator);
if (index != -1) {
entryDirPath = entryFilePath.substring(0, index);
}
else {
entryDirPath = "";
}
entryDir = new File(entryDirPath);
//如果文件夹路径不存在,则创建文件夹
if (!entryDir.exists() || !entryDir.isDirectory()) {
entryDir.mkdirs();
} //创建解压文件
entryFile = new File(entryFilePath);
if (entryFile.exists()) {
//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException
SecurityManager securityManager = new SecurityManager();
securityManager.checkDelete(entryFilePath);
//删除已存在的目标文件
entryFile.delete();
} //写入文件
bos = new BufferedOutputStream(new FileOutputStream(entryFile));
bis = new BufferedInputStream(zip.getInputStream(entry));
while ((count = bis.read(buffer, 0, 1024)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
bos.close();
}
} }
注意:在压缩文件时,如果压缩路径包含要创建的zip文件就要注意逃过同名的zip文件,否则会造成死循环。
使用Java对文件进行解压缩的更多相关文章
- java zip文件的解压缩(支持中文文件名)
用的apache的ant包,下载导入即可.由于过程比较简单,直接上代码. 代码可直接复制使用. 如果想在android上使用,记得要在AndroidManifest.xml里添加权限: <use ...
- java Zip文件解压缩
java Zip文件解压缩 为了解压缩zip都折腾两天了,查看了许多谷歌.百度来的code, 真实无语了,绝大多数是不能用的.这可能跟我的开发环境有关吧. 我用的是Ubuntu14.04,eclips ...
- Java实现压缩文件与解压缩文件
由于工作需要,需要将zip的压缩文件进行解压,经过调查发现,存在两个开源的工具包,一个是Apache的ant工具包,另一个就是Java api自带的工具包:但是Java自带的工具包存在问题:如果压缩或 ...
- Java实现对zip和rar文件的解压缩
通过java实现对zip和rar文件的解压缩
- java代理使用 apache ant实现文件压缩/解压缩
[背景] 近日在研究web邮件下载功能,下载的邮件能够导入foxmail邮件client.可是批量下载邮件还需将邮件打成一个压缩包. 从网上搜索通过java实现文件压缩.解压缩有非常多现成的样例. [ ...
- java创建文件和目录
java创建文件和目录 2013-09-04 12:56 99933人阅读 评论(7) 收藏 举报 分类: JAVA基础(10) 版权声明:本文为博主原创文章,未经博主允许不得转载. 创建文件和目 ...
- java之文件基本操作
java之文件基本操作 1 使用 BufferedReader 在控制台读取字符 public static void readChar() throws IOException{ char c; I ...
- java中文件的I/O操作
java中文件的读写操作 (一) (1)java中文件的字节转成字符读操作 FileInputStream fStream = new FileInputStream("test.txt&q ...
- java进行文件上传,带进度条
网上看到别人发过的一个java上传的代码,自己写了个完整的,附带源码 项目环境:jkd7.tomcat7. jar包:commons-fileupload-1.2.1.jar.commons-io-1 ...
随机推荐
- iOS错误整理--自定义按钮,给按钮内部赋值出现的错误
一.练习中为了实现自定义按钮,按钮中的imageView和titleLabel默认是左右排列的.在练习中自定义为上下排列. *在以下方法中重新布局按钮中的子控件 - (void)layoutSubvi ...
- Node.js获取mac网卡地址
一.关于getmac node.js没有直接获取mac网卡地址的模块,此时我们需要借助于第三方模块getmac.getmac 可以帮助我们 获取当前机器上的mac地址.gatmac 下载地址为:htt ...
- openfire安装配置完全教程
Java领域的IM解决方案 Java领域的即时通信的解决方案可以考虑openfire+spark+smack. Openfire是基于Jabber协议(XMPP)实现的即时通信服务器端,最新版本是3. ...
- 百度搜索_Selenium WebDriver 环境搭建和错误调试_chromedriver_win32必须下载否则无法测试chrome
转自: http://www.360doc.com/content/14/0821/18/597197_403634783.shtml zTree 东西不多,我也一直使用着原始的人工测试手段,随着内 ...
- ubuntu配置apache和cgi
ubuntu配置apache和cgi . 更新源并进行安装,否则后面的下载可能会不成功. sudo apt-get update sudo apt-get upgrade . 安装apache2服务 ...
- 最简单的基于FFMPEG+SDL的音频播放器 ver2 (採用SDL2.0)
===================================================== 最简单的基于FFmpeg的音频播放器系列文章列表: <最简单的基于FFMPEG+SDL ...
- erlang二进制的难理解的地方,有点神奇
40> <<A:16>> = <<1,2>>.<<1,2>>41> <<B:16/bits>> ...
- 【Java面试题】12 内部类可以引用它的包含类的成员吗?有没有什么限制?
完全可以.如果不是静态内部类,那没有什么限制! 如果你把静态嵌套类当作内部类的一种特例,那在这种情况下不可以访问外部类的普通成员变量,而只能访问外部类中的静态成员,例如,下面的代码: class Ou ...
- PHP curl_setopt函数用法介绍补充篇
1.curl数据采集系列之单页面采集函数get_html 单页面采集在数据采集过程中是最常用的一个功能 有时在服务器访问限制的情况下 只能使用这种采集方式 慢 但是可以简单的控制 所以写好一个常用的c ...
- 远程数据库备份到本地出现“Access denied for user 'root'@localhost(using password: YES)”的问题
由于另外一个人在用远程的server做测试,导致我访问这个远程机器的mysql提示“too many connections”的问题,于是想到干脆把数据库当下来做测试好了,结果用heidiSQLs进行 ...