Fail to load Image in Maven project

79 Views Asked by At

I am working on an Java Maven project and trying to load an image from resource/Image folder using ClassLoader and it fails for some reason. Everything was fine before I moved all the images from the "src/main/resource" to the "src/main/resource/Images" folder. I must change the letter case of Images to something like "images" or "IMageS" to successfully load them, which is weird.

This is the code that I use to load image

Image i = null;
URL u = GameUtil.class.getClassLoader().getResource(imagePath);
i = new Image(u.toString());

This is an path that I use, as an example "Images/candy.png"

Error Message: java.lang.NullPointerException: Cannot invoke "java.net.URL.toString()" because "u" is null

I expect that I can load the images using the exact path instead of paths that don't match the letter case of the actual folder

1

There are 1 best solutions below

4
stackoe On

I don't know what GameUtil is. Maybe you can show your success case before moving folders, otherwise I can't judge why you failed.

So, I can only show my case;

// comments: the resource location to resolve: either a "classpath:" pseudo URL, a "file:" URL, or a plain file path
org.springframework.util.ResourceUtils.getURL(String resourceLocation);

@Autowired
org.springframework.core.io.ResourceLoader loader;
//  use like this(see source code comments):
//  Resource res = loader.getResource(String loaction);
//  URL url = res.getURL();