Android 中的文件解压 – 热爱改变生活
我的GitHub GitHub |     登录
  • If you can't fly, then run; if you can't run, then walk; if you can't walk, then crawl
  • but whatever you do, you have to keep moving forward。
  • “你骗得了我有什么用,这是你自己的人生”
  • 曾有伤心之地,入梦如听 此歌

Android 中的文件解压

Android sinvader 4425℃ 0评论

在我们制作 Android 程序的时候,会有一些需求:用户要安装包尽可能的小,同时在打包 apk 的时候还要将可能用到的资源都打包到 apk 中,在尽量把资源打包到 apk 的前提下,我们可以考虑使用压缩来解决。
下面是解压的调用代码:

  1. InputStream inputStream = new FileInputStream(fileTemp);
  2. unZip(inputStream, context.getFilesDir().getAbsolutePath() + "/", true);

解压的代码:

  1. /**
  2. * @param inputStream 要解压的文件
  3. * @param outputDirectory 输出目录
  4. * @param isReWrite 是否覆盖
  5. * @throws IOException
  6. */
  7. public static void unZip(InputStream inputStream, String outputDirectory, boolean isReWrite) throws IOException {
  8. // 创建解压目标目录
  9. File file = new File(outputDirectory);
  10. // 如果目标目录不存在,则创建
  11. if (!file.exists()) {
  12. file.mkdirs();
  13. }
  14. // 打开压缩文件
  15. ZipInputStream zipInputStream = new ZipInputStream(inputStream);
  16. // 读取一个进入点
  17. ZipEntry zipEntry = zipInputStream.getNextEntry();
  18. // 使用 1Mbuffer
  19. byte[] buffer = new byte[1024];
  20. // 解压时字节计数
  21. int count = 0;
  22. // 如果进入点为空说明已经遍历完所有压缩包中文件和目录
  23. while (zipEntry != null) {
  24. // 如果是一个目录
  25. if (zipEntry.isDirectory()) {
  26. file = new File(outputDirectory + File.separator + zipEntry.getName());
  27. // 文件需要覆盖或者是文件不存在
  28. if (isReWrite || !file.exists()) {
  29. file.mkdir();
  30. }
  31. } else {
  32. // 如果是文件
  33. file = new File(outputDirectory + File.separator + zipEntry.getName());
  34. // 文件需要覆盖或者文件不存在,则解压文件
  35. if (isReWrite || !file.exists()) {
  36. file.createNewFile();
  37. FileOutputStream fileOutputStream = new FileOutputStream(file);
  38. while ((count = zipInputStream.read(buffer)) > 0) {
  39. fileOutputStream.write(buffer, 0, count);
  40. }
  41. fileOutputStream.close();
  42. }
  43. }
  44. // 定位到下一个文件入口
  45. zipEntry = zipInputStream.getNextEntry();
  46. }
  47. zipInputStream.close();
  48. }
测试代码下载
¥ 有帮助么?打赏一下~

转载请注明:热爱改变生活.cn » Android 中的文件解压


本博客只要没有注明“转”,那么均为原创。 转载请注明链接:sumile.cn » Android 中的文件解压

喜欢 (0)
发表我的评论
取消评论
表情

如需邮件形式接收回复,请注册登录

Hi,你需要填写昵称和邮箱~

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址