对.zip格式的文件进行解压缩

//第一个参数就是需要解压的文件,第二个就是解压的目录
public static boolean upZipFileDir(File zipFile, String folderPath) {
ZipFile zfile= null;
try {
//转码为GBK格式,支持中文
zfile = new ZipFile(zipFile,"GBK");
} catch (IOException e) {
e.printStackTrace();
return false;
}
Enumeration zList=zfile.getEntries();
ZipEntry ze=null;
byte[] buf=new byte[1024];
while(zList.hasMoreElements()){
ze=(ZipEntry)zList.nextElement();
//列举的压缩文件里面的各个文件,判断是否为目录
if(ze.isDirectory()){
String dirstr = folderPath + ze.getName();
dirstr.trim();
File f=new File(dirstr);
f.mkdir();
continue;
}
OutputStream os= null;
FileOutputStream fos = null;
// ze.getName()会返回 script/start.script这样的,是为了返回实体的File
File realFile = getRealFileName(folderPath, ze.getName());
try {
fos = new FileOutputStream(realFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
os = new BufferedOutputStream(fos);
InputStream is= null;
try {
is = new BufferedInputStream(zfile.getInputStream(ze));
} catch (IOException e) {
e.printStackTrace();
return false;
}
int readLen=0;
//进行一些内容复制操作
try {
while ((readLen=is.read(buf, 0, 1024))!=-1) {
os.write(buf, 0, readLen);
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
try {
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
try {
zfile.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}

/**
* 给定根目录,返回一个相对路径所对应的实际文件名.
* @param baseDir 指定根目录
* @param absFileName 相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件
*/
public static File getRealFileName(String baseDir, String absFileName){
String[] dirs=absFileName.split("/");
File ret = new File(baseDir);
String substr = null;

if(dirs.length>1){
for (int i = 0; i < dirs.length-1;i++) {
substr = dirs[i];
ret=new File(ret, substr);
}

if(!ret.exists())
ret.mkdirs();
substr = dirs[dirs.length-1];
ret=new File(ret, substr);
return ret;
}else{
ret = new File(ret,absFileName);
}
return ret;
}
注意:上面代码中的upZipFileDir方法,所用到的ZipFile类,尽可能不用java.util.zip.ZipFile,而是用org.apache.tools.zip.ZipFile。这里需要添加依赖库:compile 'org.apache.ant:ant:1.8.4'


转载于:https://www.cnblogs.com/qynprime/p/9488384.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值