0

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:

folders

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

4
  • I think you don't have to include "resources" in your request (so: getResource("/images/icon.png"); ) Commented Jan 17, 2018 at 11:20
  • also, if my suggestion does not work, I would suggest you to put a breakpoint and use the evaluator to make some try Commented Jan 17, 2018 at 11:22
  • Does not work, same issue. Commented Jan 17, 2018 at 11:22
  • 1
    Do you really need getClassLoader() at this point? this.getClass().getResource() works fine normally. Commented Jan 17, 2018 at 11:23

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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"); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.