问题
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