最近在一个项目中需要对文件进行自动的解压缩,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. CMake 用法导览

    Preface : 本文是CMake官方文档CMake Tutorial (http://www.cmake.org/cmake/help/cmake_tutorial.html) 的翻译.通过一个样 ...

  2. win7控制面板一打开就停止的解决方法

    现象:win7系统,打开控制面板后,弹出提示窗口:资源管理器停止工作,需要重启.点重启后,系统自动重建桌面进程.控制面板根本无法使用. 下面是网上找到的方法,如果都不行再参照后面我的解决方法. 1. ...

  3. jsp页面的el表达式取数据

    在jsp页面去Id时候要照上面的方式取,不能照下面的方式取:

  4. JS实现复制到剪贴板(兼容FF/Chrome/Safari所有浏览器)

    现在浏览器种类也越来越多,诸如 IE.Firefox.Chrome.Safari等等,因此现在要实现一个js复制内容到剪贴板的小功能就不是一件那么容易的事了. 在FLASH 9 时代,有一个通杀所有浏 ...

  5. Firefox 在LR录制过程中添加例外的问题解决方法

    用lr调火狐打开网页  会报证书安全问题 证书安全提示目的是告诉你这个服务器使用的证书可能不安全,要不要信任,你自己决定,不信任就不能访问.为什么会报证书安全,因为浏览器没添加该证书.或者由于性能工具 ...

  6. 自然语言交流系统 phxnet团队 创新实训 项目博客 (二)

    基本要求 打开软件,即可进入2D文本交流界面, 软件此时已经连接到服务器,点击文本输入框输入你想说的话,点击发送按钮即可进行交流,点击CHAT和STUDY分别切换到聊天模式或是学习模式,聊天模式是机器 ...

  7. 一遍记住Java常用的八种排序算法与代码实现

    1.直接插入排序 经常碰到这样一类排序问题:把新的数据插入到已经排好的数据列中. 将第一个数和第二个数排序,然后构成一个有序序列 将第三个数插入进去,构成一个新的有序序列. 对第四个数.第五个数……直 ...

  8. 在 PL/SQL 块的哪部分可以对初始变量赋予新值? (选择1项)

    A.结尾部分 B.开头部分 C.执行部分 D.声明部分 解答:C

  9. Openstack镜像和密码

    #!/bin/sh passwd ubuntu<<EOF ubuntu ubuntu EOF sed -i 's/PasswordAuthentication no/PasswordAut ...

  10. xshell-常用指令汇总 linux 常用指令

    suse linux 常用命令  (1)命令ls——列出文件  ls -la 给出当前目录下所有文件的一个长列表,包括以句点开头的“隐藏”文件  ls a* 列出当前目录下以字母a开头的所有文件  l ...