在android中以编程方式查找ZipFile中的条目数

时间:2014-06-11 07:19:10

标签: java android

我想在Zip File文件中找到条目数。 操作系统是Android。

我创建了一个像这样的ZipFile:

ZipFile zf = new ZipFile(path);

但不知怎的,我得到以下例外:

  

ZIpException:未找到EOCD:不是Zip存档

请帮我解决这个问题。

这是解压缩文件的代码。如何显示解压缩操作的进度?

FileInputStream fin = new FileInputStream(zipFile);
            ZipInputStream zin = new ZipInputStream(fin);
            ZipEntry ze = null;
            int iIndex = 0;
            while ((ze = zin.getNextEntry()) != null) {
                iIndex++;
                Log.d(TAG, "Unzipping " + iIndex + " " + ze.getName());
                try {
                    if (ze.isDirectory()) {
                        dirChecker(ze.getName(), location + SLASH);
                    } else {
                        FileOutputStream fout = new FileOutputStream(
                                location + SLASH + ze.getName());
                        byte[] buffer = new byte[8192];
                        int len;
                        while ((len = zin.read(buffer)) != -1) {
                            fout.write(buffer, 0, len);
                        }
                        fout.close();
                        zin.closeEntry();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            zin.close();
            Log.d(TAG, "unzipping completed.");

2 个答案:

答案 0 :(得分:1)

来自ZipException的文档:

  

当ZipFile和ZipInputStream抛出此运行时异常时   文件或流不是有效的zip文件。

我的猜测是你的zip文件损坏或你的路径不正确。

如果你的zip文件已损坏,你应该解决这个问题。

您可以通过调用来检查文件是否确实存在 File file = new File(path); 并且仅在file.exists()时打开ZipFile。

答案 1 :(得分:0)

基本上你尝试获取nextElement()然后从zip文件中读取它。您可以保持计数器ZipEntry类型的Enumeration循环,然后随着我们找到更多元素而递增。

ZipFile zf = new ZipFile(f);
try {
  for (Enumeration<? extends ZipEntry> e = zf.entries(); e.hasMoreElements();) {
    ZipEntry ze = e.nextElement();
    String name = ze.getName();
    if (name.endsWith(".txt")) {
         InputStream in = zf.getInputStream(ze);
    }
  }
} finally {
  zf.close();
}

您可以在Reading zip file efficiently in Java

了解更多信息