Unable to locate/open image inside exported jar

╄→尐↘猪︶ㄣ 提交于 2019-12-11 19:15:33

问题


I have explored every single solution related to this problem on Stack Overflow, and the solutions I encountered worked only in my IDE (Eclipse Mars), but when exported they all failed.

I have an image file I simply want to load from inside my exported jar.

As you can see from the project layout, Images is a folder directly inside of the project folder CooldownTrackerJava. To refer to it, I've tried a variety of methods.

//My class' name is AddItemDialog

//Method 1
String filePath = File.separator + "Images" + File.separator + "questionMark.png";
InputStream inputStream = AddItemDialog.class.getResourceAsStream(filePath);
BufferedImage img = ImageIO.read(inputStream);

I tried method 1 in a few ways. I tried it with and without the File.separator at the start of the filePath. I understand that the former refers to an absolute path, while the latter is relative. I also tried moving the Images folder inside of the directory where my class files were.

All of these failed giving me a NullPointerException when exported and tested multiple times.

//Method 2
String saveLocation = File.separator + "Images" + File.separator + "questionMark.png";    
Image img = Toolkit.getDefaultToolkit().getImage(getClass().getResource(saveLocation));

As per this post I tried the above method however it still did not work.

I've tried many variations aside from the ones mentioned in this post but none of them have been successful when I exported the jar.

Do I need to add the Images folder to my build path? Should I move it to the src folder? Am I missing one obvious step? All suggestions would be highly appreciated. Also here is the layout of the exported jar file.


回答1:


The solution was a two-part effort. Firstly, I moved my Images folder into the src directory as shown below. Kudos to Matthew.

I then removed File.separator and replaced it with a forward slash/. Thanks to fge.

Do not use File.separator(). Separators for resource paths on the class path is always /. If you use Windows you will therefore always get the wrong result.

I used a variant of method 1 to test it. Both methods will work though.

String saveLocation = "/Images/questionMark.png";
InputStream inputStream = this.getClass().getResourceAsStream(saveLocation);
try {
    BufferedImage img = ImageIO.read(inputStream);
} catch (IOException e) {
    e.printStackTrace();
}


来源:https://stackoverflow.com/questions/36269693/unable-to-locate-open-image-inside-exported-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!