java压缩解压缩ZipFile完整源码-可以直接拿来用

import java.io.File;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/*

最近在做一个上传下载的项目,如果文件特别多,目录层次也比较深,那么上传的时候最好打包成压缩文件.

下面的类封装了2个方法,createZip(String fromDir,String toZipFullname)用来创建zip文件(从源文件夹到目标zip文件).outZip(File theZipFile)用来解压zip文件到当前目录.

特别说明:本来网上已经有很多其他人写的相同功能的类了,为什么我还要发表这篇文章呢?当初,我也是准备到网上拿来就用的,可是实际运行中,发现有些会把源文件夹一起压缩进zip文件,有些甚至错误地把系统盘盘符也压进去了,有些在压缩解压的时候报FileNotFoundException拒绝访问......等等各种问题. 于是,没有办法,只好拿着别人的类+JDK_api文档慢慢研究.

值得注意的是:你必须使用下面的压缩函数对文件进行压缩,才能用下面的解压函数正确解压! windows下右键创建的压缩包是不能被这个解压函数解压的,压缩方式的不同导致了ZipEntry对象的不同(例如:是否把压缩包内文件夹算作ZipEntry条目).

*/

public class MyZip {
public static void main(String[] args) throws ZipException, IOException {
//初始化路径
String SIS = File.separator;
String root = "E:" + SIS + "_000EclipseWorkSpace" + SIS + "ScanFilesToXml";
String fromDir = root + SIS + "temp";
String toZipFullname = root + SIS + "data" + SIS + "123001.zip";
//压缩:
createZip(fromDir,toZipFullname);
//解压(完毕后删除压缩包):
// File zip = new File(toZipFullname);
// if(outZip(zip)){
// zip.delete();//实际测试时,这条语句没有执行,可以试试加个Thread.sleep(10);
// }
}
public static boolean createZip(String fromDir,String toZipFullname){
File fromFile = new File(fromDir);
List<File> fileList = new ArrayList<File>();
getAllFiles(fromFile, fileList);
writeZipFile(toZipFullname, fromFile, fileList);
return true;
}
/**
* Add a file to the zip

* @param zipfilename
* @param file
* @param zos
* @throws FileNotFoundException
* @throws IOException
*/
private static void addToZip(File zipfilename, File file, ZipOutputStream zos)
throws FileNotFoundException, IOException {


FileInputStream fis = new FileInputStream(file);


// we want the zipEntry's path to be a relative path that is relative
// to the directory being zipped, so chop off the rest of the path
String zipFilePath = file.getCanonicalPath().substring(
zipfilename.getCanonicalPath().length() + 1,
file.getCanonicalPath().length());
System.out.println("Writing '" + zipFilePath + "' to zip file");
ZipEntry zipEntry = new ZipEntry(zipFilePath);
zos.putNextEntry(zipEntry);


byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}


zos.closeEntry();
fis.close();
}
/**
* Create the zip file

* @param directoryToZip
* @param fileList
*/
private static void writeZipFile(String toFileName, File directoryToZip,
List<File> fileList) {


try {
FileOutputStream fos = new FileOutputStream(toFileName);
ZipOutputStream zos = new ZipOutputStream(fos);


for (File file : fileList) {
if (!file.isDirectory()) { // we only zip directory, not
// directories
addToZip(directoryToZip, file, zos);
}
}


zos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Read all the files recursively from the directory

* @param dir
* @param fileList
*/
private static void getAllFiles(File dir, List<File> fileList) {
try {
File[] files = dir.listFiles();
for (File file : files) {
fileList.add(file);
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
getAllFiles(file, fileList);
} else {
System.out.println("     file:" + file.getCanonicalPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 解压zip文件到当前目录

* @param theZipFile
* @return
* @throws ZipException
* @throws IOException
*/
public static boolean outZip(File theZipFile) throws ZipException, IOException {
// 所提供的File不存在或者不是文件,则直接返回false
if (!theZipFile.exists() || !theZipFile.isFile()) {
return false;
}
String SIS = File.separator; //当前系统路径分隔符
// zip所在路径
String zipPath = theZipFile.getParent();
// 建立ZipFile对象,并获取所有文件条目的枚举(文件夹不算枚举元素[不同的压缩方式,获得的条目数量不同])
ZipFile zipFile = new ZipFile(theZipFile);
Enumeration<?> enu = zipFile.entries();//该枚举只含文件,通常windows下压缩包把文件夹也算进去了
// 遍历所有枚举元素
while (enu.hasMoreElements()) {
// 获取一个枚举元素(zip中的一个文件)
ZipEntry zipEntry = (ZipEntry) enu.nextElement();
// 元素名字(不含路径)
String entryName = zipEntry.getName();
System.out.println("正在解压:"+entryName);
// 当前目录下创建空文件(用于存储解压出来的条目,如果文件在某个文件夹下,则会先创建这些文件夹)
File file = new File(zipPath, entryName);
// 如果条目在某个文件夹下,则先创建文件夹,再创建空文件
if (entryName.contains(SIS)) {
File parentFile = file.getParentFile();
if (!parentFile.exists())
parentFile.mkdirs();
}
if (!file.exists())
file.createNewFile();
// 从zip文件中读取文件存储到刚刚创建的空文件中
InputStream is = zipFile.getInputStream(zipEntry);
FileOutputStream fos = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
is.close();
fos.close();
}
// 解压完成,关闭资源
zipFile.close();
return true;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值