2009-09-22 18 views
0

我看了帖子:閱讀JAR文件的內容(在運行時)?

Viewing contents of a .jar file

How do I list the files inside a JAR file?

但我很遺憾,沒有找到很好的解決實際閱讀一個JAR的內容(由檔案文件)。

此外,有人可以給我一個提示,或指向一個資源,我的問題在哪裏討論?

我能想到的一個不那麼直接的路要做到這一點:
我可以一個JAR的資源列表某種程度上轉換成的 內-JAR的URL列表,然後我可能使用openConnection()打開。

+1

http://stackoverflow.com/questions/749533 http://stackoverflow.com/questions/435890 http://stackoverflow.com/questions/251336/is-something-similar-to-serviceloader- in-java-1-5 http://stackoverflow.com/questions/1429172/list-files-inside-a-jar http://stackoverflow.com/questions/205573/java-at-runtime-find-all- class-in-app-that-extend-a-base-class http://stackoverflow.com/questions/347248/how-can-i-get-a-list-of-all-the-implementations-of-an -interface-programmatically http://stackoverflow.com/questions/1456930/read-all-classes-from-java-package-in-classpath – erickson

回答

7

您使用JarFile打開Jar文件。有了它,你可以通過使用'getEntry(String name)'或'entires'來獲得ZipEntry或JarEntry(它們可以被看作是一樣的東西)。一旦你得到一個Entry,你可以通過調用'JarFile.getInputStream(ZipEntry ze)'來獲得InputStream。那麼你可以從流中讀取數據。

查看教程here

+0

啊,謝謝!我以某種方式完全監督JarFile的getInputStream! –

3

這是我如何讀它作爲一個ZIP文件,

try { 
     ZipInputStream is = new ZipInputStream(new FileInptuStream("file.jar")); 
     ZipEntry ze; 

     byte[] buf = new byte[4096]; 
     int len; 

     while ((ze = is.getNextEntry()) != null) { 

      System.out.println("----------- " + ze); 
      len = ze.getSize(); 

      // Dump len bytes to the file 
      ... 
     } 
     is.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

,如果你想解壓縮整個文件這比jar文件的方法更有效。

1

這裏是讀取jar文件內所有文件內容的完整代碼。

public class ListJar { 
    private static void process(InputStream input) throws IOException { 
     InputStreamReader isr = new InputStreamReader(input); 
     BufferedReader reader = new BufferedReader(isr); 
     String line; 

     while ((line = reader.readLine()) != null) { 
      System.out.println(line); 
     } 
     reader.close(); 
    } 

    public static void main(String arg[]) throws IOException { 
     JarFile jarFile = new JarFile("/home/bathakarai/gold/click-0.15.jar"); 

     final Enumeration<JarEntry> entries = jarFile.entries(); 
     while (entries.hasMoreElements()) { 
      final JarEntry entry = entries.nextElement(); 
      if (entry.getName().contains(".")) { 
       System.out.println("File : " + entry.getName()); 
       JarEntry fileEntry = jarFile.getJarEntry(entry.getName()); 
       InputStream input = jarFile.getInputStream(fileEntry); 
       process(input); 
      } 
     } 
    } 
}