![](/img/trans.png)
[英]Exporting an Eclipse Project into a Runnable Jar does not work
[英]Exporting image in runnable jar doesn't work
我在Java中遇到一個奇怪的問題。 我想創建一個可運行的jar:這是我唯一的課程:
public class Launcher {
public Launcher() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
String path = Launcher.class.getResource("/1.png").getFile();
File f = new File(path);
JOptionPane.showMessageDialog(null,Boolean.toString(f.exists()));
}
}
如您所見,它只能輸出是否可以找到該文件。 在日食下工作正常 (返回true)。 我已經用圖像1.png創建了一個源文件夾資源。 (將資源文件夾添加到構建路徑中的源中)
一旦將項目導出到可運行的jar並啟動它,它就會返回false。 我不知道為什么 有人有主意嗎? 提前致謝
編輯:我按照示例2創建資源文件夾: Eclipse導出的Runnable JAR不顯示圖像
如果您想從.jar文件中加載資源,請使用getClass().getResource()
。 這將返回具有正確路徑的URL。
Image icon = ImageIO.read(getClass().getResource("image´s path"));
要訪問jar中的圖像,請使用Class.getResource()
。
我通常會這樣做:
InputStream stream = MyClass.class.getResourceAsStream("Icon.png");
if(stream == null) {
throw new RuntimeException("Icon.png not found.");
}
try {
return ImageIO.read(stream);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
stream.close();
} catch(IOException e) { }
}
仍然您了解,請通過此鏈接。
因為圖像不是單獨的文件,而是打包在.jar中。
使用代碼從流中創建圖像
InputStream is=Launcher.class.getResourceAsStream("/1.png");
Image img=ImageIO.read(is);
嘗試使用它來獲取圖像
InputStream input = getClass().getResourceAsStream("/your image path in jar");
兩個簡單步驟:
1-將文件夾(圖像所在的位置)添加到構建路徑;
2-使用此:
InputStream url = this.getClass().getResourceAsStream("/load04.gif");
myImageView.setImage(new Image(url));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.