2012-04-15 122 views
2

我試圖從我的jar中獲取圖像。但是無論我爲getResource()提供的字符串是否總是返回null。Jar獲取圖像作爲資源

try { 
    System.out.println(Bootstrapper.class.getResource("./img/logo.png").toURI().getPath()); 
} catch (URISyntaxException ex) { 
    Logger.getLogger(CrawlerFrame.class.getName()).log(Level.SEVERE, null, ex); 


    } 
    ImageIcon ii = new ImageIcon(Bootstrapper.class.getResource("./img/logo.png")); 
    setIconImage(ii.getImage()); 

在異常線程 「AWT-EventQueue的-0」 顯示java.lang.NullPointerException 在net.sharpcode.crawler.ui.CrawlerFrame.init(CrawlerFrame.java:35) 在net.sharpcode。 crawler.ui.CrawlerFrame(CrawlerFrame.java:28) 在net.sharpcode.crawler.Bootstrapper $ 1.run(Bootstrapper.java:55)

enter image description here

我已經試過:

getResource("") 
getResource(".") 
getResource("./") 
getResource("/img/logo.png") 
Bootstrapper.class.getProtectionDomain().getCodeSource().getLocation().getPath() 
+0

什麼是你'Bootstrapper'類的包叫什麼名字? – dash1e 2012-04-15 14:46:03

+0

你需要向我們展示你的jar文件的結構。 – 2012-04-15 14:47:47

+0

@JonSkeet添加了一張結構圖。 – Reinard 2012-04-15 14:53:34

回答

5
this.getClass().getResource("/net/sharpcode/crawler/img/logo.png") 
2

擺脫 「./」 的部分 - 只需使用:

Bootstrapper.class.getResource("img/logo.png"); 

...就是如果它的相對Bootstrapper.class。如果img「目錄」是在JAR文件的根目錄,使用

Bootstrapper.class.getResource("/img/logo.png"); 
+0

它只是在使用「img/logo.png」時返回「null」 – Reinard 2012-04-15 14:50:36

+0

@SirTroll:它不應該 - 如果引導程序在net.sharpcode.crawler中... – 2012-04-15 16:20:35

0

從堆棧跟蹤我看到Bootstrapper類在於net.sharpcode.crawler包。這意味着以下路徑./img/logo.png將被解析爲/net/sharpcode/crawler/img/logo.png。我猜/img是一個頂級目錄,所以無論使用絕對路徑:

Bootstrapper.class.getResource("/img/logo.png") 

或負載通過ClassLoader

Bootstrapper.class.getClassLoader().getResource("img/logo.png") 
+0

圖像目錄位於net.sharpcode.crawler。 IMG – Reinard 2012-04-15 14:51:25