Android Zip 解压与进度 实现

这篇博客介绍了如何在Android中实现Zip文件的解压功能,包括判断并创建文件夹,创建文件,以及在解压过程中计算并显示进度。代码示例展示了如何使用ZipInputStream读取和写入文件,以及更新UI展示解压进度。
摘要由CSDN通过智能技术生成

if (mZipEntry.isDirectory()){// 如果是文件夹

pathFileName = pathFileName.substring(0,pathFileName.length() - 1);

//当层文件夹路经

currentPathFileName = outPath + File.separator + pathFileName;

//创建

new File(currentPathFileName).mkdirs();

}else {

//非文件夹直接显示

File file = new File(outPath + “/” + pathFileName);

if (!file.exists()){

file.getParentFile().mkdirs();

file.createNewFile();

}

}

}

}catch (FileNotFoundException e){

e.printStackTrace();

}catch (IOException e){

e.printStackTrace();

}

}

在这个代码中我们可以看到传入了两个参数,一个是文件的原始路径,一个是解压路径,接着,我将原始路径转为ZipInputStream后进行while循环,如果是文件夹则创建文件夹路径,不是文件夹则直接创建文件,此时如果运行的话,将会有解压功能,但是内容却是空的,因为我们的数据流还没有写入,同时我们也可以在写入的时候计算解压进度使用百分比显示,所以这里我们可以写一个接口或者其他呈现的方式,因为解压是

  • 18
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android平台上,我们可以使用java.util.zip包中的ZipInputStream类来解压有密码保护的zip文件。 首先,我们需要获取到需要解压zip文件的输入流,可以通过FileInputStream或者AssetsManager获取。接下来,我们需要创建一个ZipInputStream对象,将zip文件的输入流传入。同时,我们需要指定解压时使用的密码。可以通过调用ZipInputStream的setPassword方法来设置密码。 然后,我们可以使用ZipEntry类的getNextEntry方法来获取zip文件中的每一个文件。对于每个文件,我们可以使用ZipEntry的getName方法获取文件名,并创建一个输出流将文件写入到指定位置。同时,我们需要设置一个缓冲区用于读取zip文件的内容,并将读取到的数据写入到输出流中,直到读取完当前文件的所有内容为止。 最后,记得在使用完ZipInputStream后要进行资源的关闭操作,防止内存泄漏。 下面是一个示例代码,演示了如何解压有密码保护的zip文件: ```java import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public void unzipWithPassword(File zipFile, File destDir, String password) { FileInputStream fis = null; ZipInputStream zis = null; try { fis = new FileInputStream(zipFile); zis = new ZipInputStream(fis); zis.setPassword(password); byte[] buffer = new byte[1024]; ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) { String fileName = zipEntry.getName(); File newFile = new File(destDir.getAbsolutePath() + File.separator + fileName); // 创建目录 if (zipEntry.isDirectory()) { newFile.mkdirs(); } else { // 创建文件 newFile.getParentFile().mkdirs(); newFile.createNewFile(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile)); int len; while ((len = zis.read(buffer)) > 0) { bos.write(buffer, 0, len); } bos.close(); } zipEntry = zis.getNextEntry(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (zis != null) { zis.close(); } if (fis != null) { fis.close(); } } catch (Exception e) { e.printStackTrace(); } } } ``` 使用该方法,我们可以在Android平台上解压有密码保护的zip文件。希望对您有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值