2017-07-03 156 views
1

我不明白如何從生成的jar文件加載文件。Java從jar加載文件

這是我的代碼,它工作正常的IDE中,而不是當我運行jar:

URL url = ClassLoader.getSystemResource("."); 
    try 
    { 
     File dir = new File(url.toURI()); 
     for (File f : dir.listFiles()) 
     { 
      String fn = f.getName(); 
      if (fn.endsWith(".png")) 
      { 
       ImageView iv = new ImageView(fn); 
       // ... 
      } 
     } 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 

罐的結構是:

  • META-INF
  • de(以及帶有類文件的其餘包)
  • file1
  • file2
  • ...等等

所以這些文件直接在jar中沒有在任何子文件夾中。

回答

1

您的代碼不起作用,因爲File對象不能用於訪問jar內的文件。你可以做的是使用ZipInputStreams打開&閱讀你的jar文件和ZipEntry一起讀取你的jar中的單個文件。 此代碼可以在jar中工作,但很可能不在IDE中。在這種情況下,您可以檢測當前狀態(IDE或Jar)並相應地執行所需的加載代碼。

CodeSource src = ClientMain.class.getProtectionDomain().getCodeSource(); 

URL jar = src.getLocation(); 
ZipInputStream zip = new ZipInputStream(jar.openStream()); 
ZipEntry entry = null; 

while ((entry = zip.getNextEntry()) != null) { 
    String entryName = entry.getName(); 
    if (entryName.endsWith(".png")) { 
     BufferedImage image = ImageIO.read(zip); 
     // ... 
    } 
} 

使用的URL已經建立,我們可以判斷,如果該程序是在一個罐子或不符合這個簡單的代碼:

new File(jar.getFile()).toString().endsWith("jar")
這工作,因爲當在IDE中,(在我的情況蝕) new File(jar.getFile()).toString()回報 "D:\Java\Current%20Projects\Test\bin" 其中在一個罐子裏,我得到了 "D:\Windows%20Folders\Desktop\Test.jar"

+0

謝謝,這完美的作品! – expensne