如何从嵌套的Jar中提取.class文件?

时间:2011-04-26 09:02:40

标签: java jar nested

我有一个名为“ OuterJar.jar ”的Jar文件,其中包含另一个名为“ InnerJar.jar ”的jar,这个InnerJar包含2个名为“ Test1”的文件。课程“& “ Test2.class ”。现在我要提取这两个文件。我尝试了一些代码,但它不起作用。

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

但问题是“jarFile”obj是OuterJar文件的obj,所以在尝试获取InnerJar中存在的文件的inputStream时是不可能的。

2 个答案:

答案 0 :(得分:4)

您需要创建第二个JarInputStream来处理内部条目。 这样做你想要的:

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

答案 1 :(得分:2)

首先解压缩InnerJar.jar,然后从中提取类文件。

相关问题