loading BufferedImage with ClassLoader.getResource

2020-04-30 16:30发布

问题:

I am trying to load an image file (gif) which is stored locally in the same directory as my Eclipse java project:

ref is the relative path where the gif image is stored.

public Sprite getSprite(String ref) {
      BufferedImage sourceImage = null;
      try {
        URL url = this.getClass().getClassLoader().getResource(ref);        
        if (url == null) {
        fail("Can't find ref: "+ref);
       }
       sourceImage = ImageIO.read(url);
       } catch (IOException e) {
        fail("Failed to load: "+ref);
       }
}

The client code that uses the above method is:

public Entity(String ref,int x,int y) {
        this.sprite = ResourceManager.getSprite("sprites/alien.gif");
        this.x = x;
        this.y = y;
    }

In the Eclipse workspace and within my project directory I have a folder spriteswith the gif images stored there. But the client code always returns: Can't find ref: sprites/ship.gif

Am I doing something wrong in my approach above to load the gif image? Is there a better more straightforward way to do a file lookup in this case?

Many thanks for any advice.

回答1:

The getResource() method searches your classpath to find the file, likely the sprites directory is not in your classpath.

Try open your project properties -> Java Build Path, select Libraries tab and click on Add Class Folder button then select the parent directory of sprites.