【问题标题】:Reading files from a ZIP file in your Android assets folder从您的 Android 资产文件夹中的 ZIP 文件中读取文件
【发布时间】:2012-07-21 19:57:28
【问题描述】:

我正在使用 ZipInputStream 从位于我的 Android 资产文件夹中的 ZIP 文件中读取文件:它可以工作,但速度很慢,因为它必须使用 getNextEntry() 顺序读取它,而且有很多文件。

如果我将 ZIP 文件复制到 SD 卡上,使用 ZipFile.getEntry 时读取速度非常快,但我没有找到将 ZipFile 与资产文件一起使用的方法!

有什么方法可以快速访问资产文件夹中的 ZIP 文件吗?还是我真的必须将 ZIP 复制到 SD 卡?

(顺便说一句,如果有人想知道我为什么这样做:该应用程序大于 50 MB,所以为了在 Play 商店中获得它,我必须使用扩展 APK;但是,因为这个应用程序也应该是放入亚马逊应用商店,我必须为此使用另一个版本,因为亚马逊不支持扩展 APK,自然......我认为在两个不同位置访问 ZIP 文件将是处理这个问题的简单方法,但是唉……)

【问题讨论】:

    标签: android zip assets


    【解决方案1】:

    您可以通过以下方式创建 ZipInputStream:

    ZipInputStream zipIs = new ZipInputStream(context.getResources().openRawResource(your.package.com.R.raw.filename)); 
    ZipEntry ze = null;
    
            while ((ze = zipIs.getNextEntry()) != null) {
    
                FileOutputStream fout = new FileOutputStream(FOLDER_NAME +"/"+ ze.getName());
    
                byte[] buffer = new byte[1024];
                int length = 0;
    
                while ((length = zipIs.read(buffer))>0) {
                fout.write(buffer, 0, length);
                }
                zipIs .closeEntry();
                fout.close();
            }
            zipIs .close();
    

    【讨论】:

    • 谢谢,但正如我所写,我已经使用了ZipInputStream,但是使用getNextEntry() 在ZIP 中搜索太慢了!
    • 您是否使用缓冲区读取文件?我为我的代码提供了一个示例。对我来说效果很好。
    • 不是解压慢,是在zip文件中寻找正确的文件。 ZipInputStream 有类似 ZipFile.getEntry(filename) 的东西吗?
    【解决方案2】:

    您可以将未压缩的文件直接存储在 assets 中(即将 zip 解压到 assets/ 文件夹中)。这样,您可以直接访问这些文件,并且在您构建 APK 时无论如何都会对其进行压缩。

    【讨论】:

      【解决方案3】:

      这对我有用:

      private void loadzip(String folder, InputStream inputStream) throws IOException
      {
          ZipInputStream zipIs = new ZipInputStream(inputStream); 
          ZipEntry ze = null;
      
                  while ((ze = zipIs.getNextEntry()) != null) {
      
                      FileOutputStream fout = new FileOutputStream(folder +"/"+ ze.getName());
      
                      byte[] buffer = new byte[1024];
                      int length = 0;
      
                      while ((length = zipIs.read(buffer))>0) {
                      fout.write(buffer, 0, length);
                      }
                      zipIs.closeEntry();
                      fout.close();
                  }
                  zipIs.close();
      }
      

      【讨论】:

        猜你喜欢
        • 2018-01-19
        • 2011-01-22
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-11
        相关资源
        最近更新 更多