我正在尝试加载与我的 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 图像的方法中做错了吗?在这种情况下,是否有更好更直接的方法来进行文件查找?
非常感谢您的任何建议。