2012-03-16 77 views
0

我有一個第三方jar包含一些我想要處理的xml文件。我不知道xml文件的名稱或編號 ,但我知道它們在jar中打包的文件夾。在jar文件中列出xml文件

URL url = this.class.getResource("/com/arantech/touchpoint/index"); 
System.out.println(url.toString()); 

這似乎返回一個有效的文件(文件夾)路徑

jar:file:/home/.m2/repository/com/abc/tp-common/5.2.0/tp-common-5.2.0.jar!/com/abc/tp/index 

但是當我試圖列出文件夾中的文件,我總是得到一個NullPointerException

File dir = new File(url.toString()); 
System.out.println(dir.exists()); 
System.out.println(dir.listFiles().length); 

任何指導意見?

+0

這*不*有效的文件夾路徑,這是一個指向一個JAR文件中的資源的合成URL。您不能將JAR文件的內容視爲自己的文件。 – skaffman 2012-03-16 16:59:38

+0

可能的重複[如何列出JAR文件中的文件?](http://stackoverflow.com/questions/1429172/how-do-i-list-the-files-inside-a-jar-file) – skaffman 2012-03-16 17:00:29

回答

0

罐是一個ZIP文件,所以罐中列出文件可以用做:

ZipFile zipFile = new ZipFile("your.jar"); 
Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); 
while (zipEntries.hasMoreElements()) { 
    System.out.println(zipEntries.nextElement().getName()); 
} 

ZipEntry.getName()包含進入路徑(儘管它沒有記錄),因此可以檢測出你需要使用的東西的那些像String.startsWith("your/path")

1

有了這個,你可以穿越主文件夾:

URL url = this.class.getResource("/com/arantech/touchpoint/index"); 
JarFile jar;  
System.out.println("Loading JAR from: " + url.toString()); 

JarURLConnection URLcon = (JarURLConnection)(url.openConnection()); 
jar = URLcon.getJarFile(); 

Enumeration<JarEntry> entries = jar.entries(); 
while (entries.hasMoreElements()) 
{ 
    JarEntry entry = (JarEntry) entries.nextElement(); 
    if (entry.isDirectory() || !entry.getName().toLowerCase().endsWith(".xml")) 
    continue; 

    InputStream inputStream = null; 
    try 
    { 
    inputStream = jar.getInputStream(entry); 
    if (inputStream != null) 
    { 
     // TODO: Load XML from inputStream 
    } 
    } 
    catch (Exception ex) 
    { 
    throw new IllegalArgumentException("Cannot load JAR: " + url); 
    } 
    finally 
    { 
    if (inputStream != null) 
     inputStream.close();   
    } 
} 
jar.close();