我正在尝试加载一个图像文件(gif),该文件本地存储在与我的Eclipse java项目相同的目录中:
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图像吗?在这种情况下,有更好的更直接的方法来进行文件查找吗?
非常感谢您的任何建议。
答案 0 :(得分:3)
getResource()
方法搜索类路径以查找文件,可能 sprites 目录不在您的类路径中。
尝试打开您的项目属性 - > Java Build Path
,选择Libraries
标签,然后点击Add Class Folder
按钮,然后选择 sprites 的父目录。