开发者

loading BufferedImage with ClassLoader.getResource()

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 s开发者_开发问答tored.

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜