Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - .jar failing to find resources (images, fonts)

I can't seem to find the correct combination of path and class vs. ClassLoader. Here is the directory structure of my project:

  • build/classes/project/MainClass.class
  • build/classes/resources/images/an_image.png
  • build/classes/resources/ImageLoader.class

The source for the ImageLoader is as follows:

public class ImageLoader {

 public ImageLoader(){...}

 public BufferedImage loadImage(String fileName) {
     String loc = "resources" + File.separator + "images" + File.separator;
     URL imgURL = this.getClass().getResource(loc + fileName);
     BufferedImage img = null;
        try {
           img = ImageIO.read(imgURL);
        } catch (IOException e) {...}
        return img;
     }
  }

I'm not entirely sure what the difference would be between that and this.getClass().getClassLoader().getResource(), but I have tried it with various combinations of paths and I simply can't seem to get the .jar to find and load the resources.

Where am I going wrong?

Thanks.

like image 739
rtheunissen Avatar asked Nov 24 '25 14:11

rtheunissen


1 Answers

Don't use File.separator for getting at a resource, it should always be '/'. It might pay to also add a leading '/' to indicate that the resource can be found from the 'top' of the class-path structure (as opposed to a sub-directory of the class that is trying to load it).

like image 84
Andrew Thompson Avatar answered Nov 27 '25 03:11

Andrew Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!