如何检查一个文件是否存在于zip压缩包中?

6

如何检查zip归档文件中是否存在某个文件?
例如,检查app.apk是否包含classes.dex
我希望找到一个使用Java NIO.2 Path的解决方案,如果可能的话,不需要提取整个归档文件。

我已经尝试过了,但没有成功:

Path classesFile = Paths.get("app.apk", "classes.dex");  // apk file with classes.dex
if (Files.exists(apkFile))  // false!
    ...
3个回答

5
我的解决方案是:
Path apkFile = Paths.get("app.apk");
FileSystem fs = FileSystems.newFileSystem(apkFile, null);
Path dexFile = fs.getPath("classes.dex");
if (Files.exists(dexFile))
    ...

2
您可以尝试使用ZipInputStream。使用方法如下:
    ZipInputStream zip = new ZipInputStream(Files.newInputStream(
            Paths.get(
                    "path_to_File"),
            StandardOpenOption.READ));
    ZipEntry entry = null;

    while((entry = zip.getNextEntry()) != null){
        System.out.println(entry.getName());
    }

0

另一个例子:

      try {

         //open the source zip file
         ZipFile sourceZipFile = new ZipFile(f);

         //File we want to search for inside the zip file
         String searchFileName = "TEST.TXT";

         //get all entries
         Enumeration e = sourceZipFile.entries();
         boolean found = false;

         System.out.println("Trying to search " + searchFileName + " in " + sourceZipFile.getName());

         while(e.hasMoreElements())
         {
            ZipEntry entry = (ZipEntry)e.nextElement();

            if(entry.getName().indexOf(searchFileName) != -1)
            {

               found = true;
               System.out.println("Found " + entry.getName());

            }
         }

         if(found == false)
         {
            System.out.println("File " + searchFileName + " Not Found inside ZIP file " + sourceZipFile.getName());
         }

         //close the zip file
         sourceZipFile.close();
      }
      catch(IOException ioe) {
         System.out.println("Error opening zip file" + ioe);
      }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接