【问题标题】:How to open a zip file and iterate through each compressed file on Android?如何在Android上打开一个zip文件并遍历每个压缩文件?
【发布时间】:2014-03-01 02:32:56
【问题描述】:

我的res/raw 目录中有一个压缩文件。我想打开 zip 文件并遍历其中存储的文本文件。我不想提取文件并将其写入设备;我只想打开 zip 文件,遍历每个文本文件中的行,然后关闭 zip 文件。

由于openRawResource 方法返回InputStream,我在尝试读取该zip 文件时遇到问题。我试图将流转换为ZipInputStream,但我不知道下一步该做什么。

在这种情况下如何创建ZipFile 对象?

这并不多,但这是我目前所拥有的:

InputStream in = getResources().openRawResource(R.raw.primes);
ZipInputStream zin = new ZipInputStream(in);
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
  // TODO
}

【问题讨论】:

    标签: java android zip


    【解决方案1】:

    您可以仅使用路径创建ZipFile,然后使用ZipInputStream 将每个条目放入BufferedReader,如下所示:

        ZipFile zipFile = new ZipFile("file_path");
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
    
        while(entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            System.out.println(zipEntry.getName());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));
            String line;
            while((line = bufferedReader.readLine()) != null){
                System.out.println(line);
            }
            bufferedReader.close();
        }
        zipFile.close();
    }
    

    要在 res/raw 中获取文件,您必须执行以下操作:

    getResources().getIdentifier("myfile","raw", getPackageName()); //for res/raw/myfile.zip
    

    【讨论】:

    【解决方案2】:

    我找到了我需要的东西here。回答问题的人建议使用ZipInputStream 中的read 方法,并将条目的内容读入StringBuffer。

    【讨论】:

      【解决方案3】:

      试试这样的:

      public static void unzip(File zipFile) throws IOException {
      
          byte[] buff = new byte[1024];
          ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
          ZipEntry ze;
      
          while ((ze = zis.getNextEntry()) != null) {
              if (!ze.isDirectory()) {                
                  while (zin.read(buff) >= 0)
                      // Do something with buff
      
              zis.closeEntry();
          }
      
          zis.close();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-29
        • 1970-01-01
        • 1970-01-01
        • 2016-05-05
        • 2022-10-07
        • 1970-01-01
        • 1970-01-01
        • 2011-10-04
        相关资源
        最近更新 更多