java - 如何在简单的 Java 项目中加载图像?

标签 java

我的项目中有这样的结构:

enter image description here

我的代码就是这样:

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/

相关文章:

java - 如何与其他方法同时运行 KeyListener?

java - 确保 Swing GUI 与底层数据结构保持同步

java - 将图像从 Android 发布到 wcf rest 服务

java - 具有多个策略的 Gson FieldNamingStrategy

JavaFX 绑定(bind)到嵌套列

java - Collection.stream() 的实现

java - 在 Java 中多次使用 "this"关键字

java - 当构造函数的两个变量丢失时,如何将对象赋予数组?

java - LDAP 和 Java : how to check if PagedResultsControl and/or VLV are available

java - Java 中的泛型类参数