How to extract .class files from nested Jar?

大憨熊 提交于 2020-01-23 02:24:48

问题


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.



来源:https://stackoverflow.com/questions/5788158/how-to-extract-class-files-from-nested-jar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!