最近在一个项目中需要对文件进行自动的解压缩,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对文件进行解压缩的更多相关文章

  1. java zip文件的解压缩(支持中文文件名)

    用的apache的ant包,下载导入即可.由于过程比较简单,直接上代码. 代码可直接复制使用. 如果想在android上使用,记得要在AndroidManifest.xml里添加权限: <use ...

  2. java Zip文件解压缩

    java Zip文件解压缩 为了解压缩zip都折腾两天了,查看了许多谷歌.百度来的code, 真实无语了,绝大多数是不能用的.这可能跟我的开发环境有关吧. 我用的是Ubuntu14.04,eclips ...

  3. Java实现压缩文件与解压缩文件

    由于工作需要,需要将zip的压缩文件进行解压,经过调查发现,存在两个开源的工具包,一个是Apache的ant工具包,另一个就是Java api自带的工具包:但是Java自带的工具包存在问题:如果压缩或 ...

  4. Java实现对zip和rar文件的解压缩

    通过java实现对zip和rar文件的解压缩

  5. java代理使用 apache ant实现文件压缩/解压缩

    [背景] 近日在研究web邮件下载功能,下载的邮件能够导入foxmail邮件client.可是批量下载邮件还需将邮件打成一个压缩包. 从网上搜索通过java实现文件压缩.解压缩有非常多现成的样例. [ ...

  6. java创建文件和目录

    java创建文件和目录 2013-09-04 12:56 99933人阅读 评论(7) 收藏 举报  分类: JAVA基础(10)  版权声明:本文为博主原创文章,未经博主允许不得转载. 创建文件和目 ...

  7. java之文件基本操作

    java之文件基本操作 1 使用 BufferedReader 在控制台读取字符 public static void readChar() throws IOException{ char c; I ...

  8. java中文件的I/O操作

    java中文件的读写操作 (一) (1)java中文件的字节转成字符读操作 FileInputStream fStream = new FileInputStream("test.txt&q ...

  9. java进行文件上传,带进度条

    网上看到别人发过的一个java上传的代码,自己写了个完整的,附带源码 项目环境:jkd7.tomcat7. jar包:commons-fileupload-1.2.1.jar.commons-io-1 ...

随机推荐

  1. Nginx_lua缓存问题,关闭lua_code_cache

    打开nginx.conf配置server{ lua_code_cache off; //关闭lua缓存 重启后生效 server_name localhost; default_type 'text/ ...

  2. java-事务-案例

    项目结构: 数据库: /* SQLyog Ultimate v12.09 (64 bit) MySQL - 5.5.53 : Database - threadlocal ************** ...

  3. java-过滤器Filter_多个Filter的执行顺序

    http://www.cnblogs.com/HigginCui/p/5772514.html [Filter链] *在一个web应用中,可以开发编写多个Filter,这些Filter组合起来称为一个 ...

  4. Java-DBCP连接池

    创建项目: 导入jar包: 参见上图. JDBCConn.java获取数据源类: package com.gordon.jdbcconn; import java.io.InputStream; im ...

  5. Java 获取webapp,Root,classpath,项目等路径工具类

    public class UtilPath { public static void main(String[] args) { String systemName = System.getPrope ...

  6. jQuery Form插件详解

    <script src="js/jquery.form.js" type="text/javascript"></script> Jqu ...

  7. loadrunner -56992

    设置Run-time Settings ,network speed ,use bandwidth为 512: 回放脚本没有报错,5个并发运行场景报如下错误: vuser_init.c(12): Er ...

  8. 《FPGA全程进阶---实战演练》第二章之硬件平台的搭建

    学习FPGA,多多少少应该要懂得硬件电路的设计,这样不单单增加了自己的技能,而且还能够对FPGA的硬件实现有更好的了解. 1 模块划分 对于一个基本的FPGA硬件平台,常用的几个电路部分:(1)电源电 ...

  9. 【转载】WebApi 接口测试工具:WebApiTestClient

    正文 前言:这两天在整WebApi的服务,由于调用方是Android客户端,Android开发人员也不懂C#语法,API里面的接口也不能直接给他们看,没办法,只有整个详细一点的文档呗.由于接口个数有点 ...

  10. Android ListView使用BaseAdapter与ListView的优化 (转至 http://www.open-open.com/lib/view/open1339485728006.html)

    在ListView的使用中,有时候还需要在里面加入按钮等控件,实现单独的操作.也就是说,这个ListView不再只是展示数据,也不仅仅是这一行要来处理用户的操作,而是里面的控件要获得用户的焦点.读者可 ...