在 Java 應用程式中讀取資源檔(圖片、配置檔等)時,開發環境與打包後的 JAR 執行環境路徑不同,常導致資源找不到。
Image image = Toolkit.getDefaultToolkit().getImage("C:/project/res/a.gif"); // 僅開發機有效
public void init() {
// 相對於當前類的包路徑載入資源
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("a.gif"));
ImageIcon icon = new ImageIcon(image);
bt.setIcon(icon);
String className = this.getClass().getName();
System.out.println(className);
this.add(bt);
this.setSize(300, 300);
setVisible(true);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
System.exit(0);
}
});
}
getClass().getResource("a.gif") 以類所在包為基準尋找資源,打包進 JAR 後仍能正確定位。getClass().getResource("/a.gif")(以類路徑根為基準)。ClassLoader.getSystemResource() 同樣以類路徑根為基準,不需前綴 /。src/main/resources(Maven 標準目錄),編譯自動複製至 target/classes,打包進 JAR 根目錄。Thread.currentThread().getContextClassLoader()。Class.getResource() 或 ClassLoader.getResource() 載入資源。