[英]getClass() getResource returning null
當我嘗試從 eclipse 中的資源目錄加載圖像時,我不斷收到空指針異常 (NPE)。 res 文件夾位於項目目錄中。 這是我獲得 NPE 的地方:
image.setIcon(new ImageIcon(new ImageIcon(this.getClass().getResource("res/bg.jpg")).getImage().getScaledInstance(image.getWidth(), image.getHeight(), Image.SCALE_SMOOTH)));
當我刪除 getClass().getReource() 圖像返回:
image.setIcon(new ImageIcon(new ImageIcon(("res/bg1.jpg")).getImage().getScaledInstance(image.getWidth(), image.getHeight(), Image.SCALE_SMOOTH)));
當我打印 res 目錄的 URL 時,我得到空值:
URL resource = this.getClass().getResource("/");
resource.getFile(); // print me somehwere
URL resource1 = this.getClass().getResource("/res");
resource.getFile(); // print me as well
URL resource2 = this.getClass().getResource("res/bg2");
resource.getFile(); // print me as well
System.out.println("Reource1 : " + resource);
System.out.println("Reource1 : " + resource1);
System.out.println("Reource1 : " + resource2);
輸出:
資源 1 :file:/C:/Users/cmooney/eclipse-workspace/TextSimplifier/bin/
資源 1:空
資源 1:空
我已經多次刷新、清理和構建該項目。
知道為什么會這樣嗎?
謝謝
來自官方 Java 文檔: https : //docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResource-java.lang.String-
查找具有給定名稱的資源。 搜索與給定類相關聯的資源的規則由類的定義類加載器實現。 此方法委托給此對象的類加載器。 如果此對象由引導類加載器加載,則該方法委托給 ClassLoader.getSystemResource(java.lang.String)。
在委托之前,使用以下算法從給定的資源名稱構造一個絕對資源名稱:
如果名稱以“/”(“\/”)開頭,則資源的絕對名稱是“/”后面的名稱部分。
否則,絕對名稱采用以下形式:
修改包名稱/名稱
其中 modified_package_name 是此對象的包名稱,其中 '/' 替換了 '.' ('\.')。
將this.getClass().getResource("res/bg.jpg")
替換為this.getClass().getResource("res/bg.jpg")
this.getClass().getResource("../res/bg.jpg")
由於this.getClass().getResource("/")
返回file:/C:/Users/cmooney/eclipse-workspace/TextSimplifier/bin/
,您需要在目錄結構中向上一級(目錄),以便您可以進入res
目錄。 它就像cd ../res
從file:/C:/Users/cmooney/eclipse-workspace/TextSimplifier/bin/
的當前位置file:/C:/Users/cmooney/eclipse-workspace/TextSimplifier/bin/
注意:我在您附加的屏幕截圖bg.jpg
不到bg.jpg
。 確保您在此路徑中有bg.jpg
。
我想,你弄錯了目錄結構。 如果“/”指向 bin 目錄,如第一個資源的輸出所示,“/res”指向 bin 的 res 子目錄,而不是 bin 父目錄中的同級目錄。
您需要移動 res 目錄或更改“/”的分辨率工作方式。
搜索與給定類相關聯的資源的規則由類的定義類加載器實現。
來自Java 文檔
對於基於 maven 的項目,資源目錄通常是 src/main/resources。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.