Question

I have a JAR file and I want to search for the presence of a class file in it.

import java.util.jar.*;

 public class Check
 {
     public static void main(String args[])  throws Exception
     {
         String path="C:\\workspace\\Project\\sun\\tools\\jam-dt.jar";
         path=path.replace("\\","/");
         JarFile jar=new JarFile(path);

         JarEntryentry=jar.getJarEntry("com/sun/xml/ws/binding/Bind.class");
    if(entry!=null)
    {
        System.out.println(" Entry present");

    }
    else
    {
        System.out.println("No Entry");
    }
}

}

However there are many directories present inside the JAR file. I cant manually enter each one of them in getJarEntry function and check.How to check if a class is present. How do I search for a file within a JAR?

Was it helpful?

Solution

String path="C:/Users/hussain.wahid/Desktop/hussain back up/Hussain/Eclipse WorkSpace/SO/poi.jar";
         path=path.replace("\\","/");
         JarFile jar=new JarFile(path);
         ArrayList<String> fileNameList = new ArrayList<String>();

         Enumeration<JarEntry> myEntry = jar.entries();
         while(myEntry.hasMoreElements())
         {
             //System.out.println(myEntry.nextElement().toString());
             fileNameList.add(myEntry.nextElement().toString());
         }
         System.out.println(fileNameList.contains("com/sun/xml/ws/binding/Bind.class"));
        //org/apache/poi/hssf/record/aggregates/

i tried to make it simpler to understand

btw introducing the arraylist is completely un-necessary

    Enumeration<JarEntry> myEntry = jar.entries();
             while(myEntry.hasMoreElements())
             {
System.out.println(myEntry.nextElement().toString().equals("org/apache/poi/hssf/record/aggregates/"));
             }

OTHER TIPS

Use JarFile.entries() and iterate over them.

You can use the below linux command to search for a class in a jar file:

jar -tvf myjar.jar | grep com.sun.xml.ws.binding.Bind.class

On Windows a few years back I use to run this from the command line:

for /R %G in (*.jar) do @jar -tvf "%G" | find "someFileNameNoExtension" > NUL && echo "%G"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top