Loading images in a jar

ぐ巨炮叔叔 提交于 2020-01-16 18:19:31

问题


I am using eclipse and I use the following code to load my image from a folder.

getClass().getResource("/images/image.jpg").getFile())

The image folder is located inside the bin folder in the project folder. It works fine when loading in eclipse, but when I export it to a jar it does not load. I have tried puting the image folder in all possible places in the jar, but it does not.

How do I load an image folder in a jar?


回答1:


You can use getResourceAsStream() method instead to get InputStream instance with your file data.

UPDATE: Loading of files from a jar happens with the help of class loader. And it can give you instance of InputStream (not FileInputStream) of any internal resource (be it image file or sound file or text file). File writing shouldn't work inside jar.




回答2:


Use this. This method doesn't return immediately.

public Image getImage(String img){
    return new ImageIcon(getClass().getResource(img)).getImage();
}

If you want to load from the root of the JAR, then

return new ImageIcon(getClass().getClassLoader().getResources(img)).getImage();


来源:https://stackoverflow.com/questions/12437752/loading-images-in-a-jar

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