2011-04-26 42 views
3

我有一個名爲 「OuterJar.jar」 的JAR文件包含一個名爲 「InnerJar.jar」 另一個罐子這個InnerJar包含2個文件名爲 「Test1.class」 & 「Test2.class」。現在我想提取這兩個文件。我嘗試了一些代碼,但它不起作用。如何從嵌套Jar中提取.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(); 

但問題是,「jar文件」 obj是OuterJar的OBJ文件,從而試圖讓存在於InnerJar文件的InputStream的時候是不可能的。

回答

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

@ WhiteFang34您的解決方案幫助我80%,因此,首先非常感謝你much.Now 2ndly我不想創建通過FileOutputStream中的另一個文件,我需要具備的JarEntry的InputStream的.hear在你的代碼中,我需要得到ze2的inputStream,所以幫助更多。 – zaree 2011-04-27 05:02:28

+0

@zaree:沒問題。在我的例子中,你想使用'jin2'作爲''InputStream'作爲內部'ze2'項。我只寫了它到另一個文件來顯示並測試它的工作原理。 – WhiteFang34 2011-04-27 05:07:17

+0

@ WhiteFang34首先你不能實例化InputStream並且讓我說如果我在InputStream中執行類似的操作= new FileInputStream(ze2.getName()。toStreing());那麼它沒有采取,如果把jin2變成FileInputStream而不是JarInputStream,那麼這不起作用b/c我們需要打開jar文件來獲取文件的innerjar條目,所以不能達到確切的點!請更新你的代碼片段。 – zaree 2011-04-27 05:48:11

2

首先提取InnerJar.jar,然後從中提取類文件。