Java: getResource image, cannot be found.

白昼怎懂夜的黑 提交于 2019-12-13 08:14:52

问题


I just came up with an error in Java (using Eclipse). I want to load an image from the resource folder into the application. Using the follwoing lines:

URL url = this.getClass().getClassLoader().getResource("/resources/images/icon.png");
BufferedImage i = ImageIO.read(url);

But this results in a java.lang.IllegalArgumentException: input == null! exception.

My folder structure is:

How can I access this image? Thank you a lot!


回答1:


getResource() returns null if it can't find the resource on the classpath.

In order to use getResource() you need the resources to be on the classpath. The resources directory isn't on the classpath. In Eclipse, you could add the resources folder to the classpath. Or create a new package images under srcServer and move the icon out of resources and into srcServer\images along with your source code.

Another way would be to load the image using a File rather than loading it as a classpath resource.




回答2:


I believe the reason why it doesn't find the resource is due to your syntax. getClass().getClassLoader().getResource() takes the input without the leading '/' and always starts at the root of the classpath. getClassLoader().getResource() is always an absolute path, whereas getClass().getResource() is a relative path.

Just use:

URL url = this.getClass().getResource("/images/icon.png"); 


来源:https://stackoverflow.com/questions/48299812/java-getresource-image-cannot-be-found

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