我的项目中有这样的结构:
我的代码就是这样:
public class ChapterTwo {
public static void main( String[] args )
{
try {
//File imageFile = new File("../../../../resources/lena.jpg");
String image = ChapterTwo.class.getResource("resources/lena.jpg").toExternalForm();
System.out.println(image);
//MBFImage image = ImageUtilities.readMBF(imageFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
现在这已经让我发疯了。让java在简单的目录结构中定位图像有多难?
我尝试过:
resources/lena.jpg
/resources/lena.jpg
../resources/lena.jpg
../../../../../resources/lena.jpg
没有任何作用。当我加载文件并调用 exists()
时,它总是返回 false。如何加载该图像?
PS:我的代码只是测试代码,但你明白了,我正在尝试各种东西。
它是 com.foo
而不是 com
编辑: 从答案来看:
String imagePath = ChapterTwo.class.getClassLoader().getResource("lena.jpg").toExternalForm();
File imageFile = new File(imagePath);
System.out.println(imageFile.exists());
我得到假
....
最佳答案
String image = ChapterTwo.class.getClassLoader().getResource("lena.jpg").getPath();
关于java - 如何在简单的 Java 项目中加载图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31765097/