How to extract .class files from nested Jar?

2020-07-21 08:32发布

问题:

I have a Jar file named "OuterJar.jar" that contains another jar named "InnerJar.jar" this InnerJar contains 2 files named "Test1.class" & "Test2.class".Now i want to extract these two files. I have tried some piece of code but it doesn't work.

class NestedJarExtractFactory{

  public void nestedJarExtractor(String path){

    JarFile jarFile = new JarFile(path);


     Enumeration entries = jarFile.entries();

          while (entries.hasMoreElements()) {

           JarEntry  _entryName = (JarEntry) entries.nextElement();

                      if(temp_FileName.endsWith(".jar")){

        JarInputStream innerJarFileInputStream=new JarInputStream(jarFile.getInputStream(jarFile.getEntry(temp_FileName)));
        System.out.println("Name of InnerJar Class Files::"+innerJarFileInputStream.getNextEntry());
       JarEntry innerJarEntryFileName=innerJarFileInputStream.getNextJarEntry();
///////////Now hear I need some way to get the Input stream of this class file.After getting inputStream i just get that class obj through 
           JavaClass clazz = new ClassParser(InputStreamOfFile,"" ).parse();

}

///// I use the syntax 
  JavaClass clazz = new ClassParser(jarFile.getInputStream(innerJarEntryFileName),"" ).parse();

But the problem is that the "jarFile" obj is the obj of OuterJar File so when trying to get the inputStream of a file that exists in the InnerJar is not possible.

回答1:

You need to create a second JarInputStream to process the inner entries. This does what you want:

FileInputStream fin = new FileInputStream("OuterJar.jar");
JarInputStream jin = new JarInputStream(fin);
ZipEntry ze = null;
while ((ze = jin.getNextEntry()) != null) {
    if (ze.getName().endsWith(".jar")) {
        JarInputStream jin2 = new JarInputStream(jin);
        ZipEntry ze2 = null;
        while ((ze2 = jin2.getNextEntry()) != null) {
            // this is bit of a hack to avoid stream closing,
            // since you can't get one for the inner entry
            // because you have no JarFile to get it from 
            FilterInputStream in = new FilterInputStream(jin2) {
                public void close() throws IOException {
                    // ignore the close
                }
            };

            // now you can process the input stream as needed
            JavaClass clazz = new ClassParser(in, "").parse();
        }
    }
}


回答2:

Extract the InnerJar.jar first, then extract the class files from it.



标签: java jar nested