How to check that file exists inside a zip archive?
Asked Answered
A

3

6

How to check that file exists inside a zip archive?
For example, check whether app.apk contains classes.dex.
I want to find a solution that uses Java NIO.2 Path and without extracting the whole archive if possible.

I've tried and it didn't work:

Path classesFile = Paths.get("app.apk", "classes.dex");  // apk file with classes.dex
if (Files.exists(apkFile))  // false!
    ...
Articular answered 7/9, 2015 at 10:3 Comment(0)
A
5

My solution is:

Path apkFile = Paths.get("app.apk");
FileSystem fs = FileSystems.newFileSystem(apkFile, null);
Path dexFile = fs.getPath("classes.dex");
if (Files.exists(dexFile))
    ...
Articular answered 7/9, 2015 at 10:13 Comment(0)
R
2

You can try ZipInputStream. Usage is as follows :-

    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());
    }
Radioactivity answered 7/9, 2015 at 11:11 Comment(0)
W
0

Another example:

      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);
      }
While answered 6/8, 2021 at 13:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.