【问题标题】:How to check that file exists inside a zip archive?如何检查该文件是否存在于 zip 存档中?
【发布时间】:2015-12-02 20:22:48
【问题描述】:

如何检查 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!
    ...

【问题讨论】:

    标签: java zip file-exists nio2


    【解决方案1】:

    我的解决办法是:

    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());
          }
      

      【讨论】:

        【解决方案3】:

        另一个例子:

              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);
              }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-10
          • 2016-10-11
          • 2022-06-07
          • 2021-07-22
          相关资源
          最近更新 更多