Android Zip文件解压代码

我们在日常生活中会用到解压缩,这个是非常重要的,那么我们在android系统中有没有解压缩那。如果有的话,那我们如何实现Zip文件的解压缩功能呢? 那么我们就看看下面的解析吧,因为Android内部已经集成了zlib库,对于英文和非密码的Zip文件解压缩还是比较简单的,下面给大家一个解压缩zip的java代码,可以在Android上任何版本中使用,Unzip这个静态方法比较简单,参数一为源zip文件的完整路径,参数二为解压缩后存放的文件夹。希望这段代码能教会大家解压缩。


private static void Unzip(String zipFile, String targetDir) {
int BUFFER = 4096; //这里缓冲区我们使用4KB,
String strEntry; //保存每个zip的条目名称

try {
BufferedOutputStream dest = null; //缓冲输出流
FileInputStream fis = new FileInputStream(zipFile);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry; //每个zip条目的实例


while ((entry = zis.getNextEntry()) != null) {


try {
Log.i("Unzip: ","="+ entry);
int count;
byte data[] = new byte[BUFFER];
strEntry = entry.getName();


File entryFile = new File(targetDir + strEntry);
File entryDir = new File(entryFile.getParent());
if (!entryDir.exists()) {
entryDir.mkdirs();
}


FileOutputStream fos = new FileOutputStream(entryFile);
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
zis.close();
} catch (Exception cwj) {
cwj.printStackTrace();
}
}


上面是Android开发网总结的zip文件解压缩代码,希望你大家有用,需要注意的是参数均填写完整的路径,比如/mnt/sdcard/xxx.zip这样的类型。


下面的方法是,解压只有一个文件组成的zip到当前目录,并且给解压出的文件重命名:


public static void unzipSingleFileHereWithFileName(String zipPath, String name) throws IOException{
File zipFile = new File(zipPath);
File unzipFile = new File(zipFile.getParent() + "/" + name);
ZipInputStream zipInStream = null;
FileOutputStream unzipOutStream = null;
try {
zipInStream = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry zipEntry = zipInStream.getNextEntry();
if (!zipEntry.isDirectory()) {
unzipOutStream = new FileOutputStream(unzipFile);
byte[] buf = new byte[4096];
int len = -1;
while((len = zipInStream.read(buf)) != -1){
unzipOutStream.write(buf, 0, len);
}
}
} finally {
if(unzipOutStream != null){
unzipOutStream.close();
}


if (zipInStream != null) {
zipInStream.close();
}
}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值