0

我正在尝试加载与我的 Eclipse java 项目本地存储在同一目录中的图像文件 (gif):

ref是存储gif图像的相对路径。

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);
       }
}

使用上述方法的客户端代码是:

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

在 Eclipse 工作区和我的项目目录中,我有一个文件夹sprites,其中存储了 gif 图像。但是客户端代码总是返回:Can't find ref: sprites/ship.gif

我在上面加载 gif 图像的方法中做错了吗?在这种情况下,是否有更好更直接的方法来进行文件查找?

非常感谢您的任何建议。

4

1 回答 1

3

getResource()方法搜索您的类路径以查找文件,可能sprites目录不在您的类路径中。

尝试打开您的项目属性-> Java Build Path,选择Libraries选项卡并单击按钮,然后选择spritesAdd Class Folder的父目录。

于 2009-11-25T19:37:15.243 回答