【问题标题】:Java ImageIO.read(getClass().getResource()) returns nullJava ImageIO.read(getClass().getResource()) 返回 null
【发布时间】:2021-12-15 19:59:56
【问题描述】:

线

andImg = ImageIO.read(getClass().getResource("gate_and.png"));

失败

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!

我使用的是Eclipse,在bin文件夹下的导航视图中有gate_and.png文件,提示该文件在构建路径中。

在我的包资源管理器视图中

project/src/view/class  - This is the class that has the code above.

project/images/gate_and.png

我右键单击项目文件夹 > 构建路径 > 链接源以将图像文件夹添加为源,再次执行此操作会提供确认消息,说明图像已在源中。

我也试过把gate_and.png改成images/gate_and.png和/images/gate_and.png,但是由于图片gate_and.png在bin文件夹下,我觉得原来是对的。

【问题讨论】:

    标签: java image ubuntu resources


    【解决方案1】:

    假设你的课程在包view.random.name中,那么

    getClass().getResource("gate_and.png")
    

    将在中查找资源

    /view/random/name/gate_and.png
    

    相对于类路径的根。您显然没有该名称的资源。

    通过将project/images 设置为构建路径条目,Eclipse 将在类路径中包含其中的所有内容。因此,您的资源将出现在

    /gate_and.png
    

    您可以通过

    访问它
    getClass().getResource("/gate_and.png")
    

    注意前面的/,这意味着开始查看类路径的根,即。这是一条绝对路径。

    所有这些规则都在javadoc 中进行了解释。

    【讨论】:

      猜你喜欢
      • 2019-05-13
      • 2014-12-24
      • 2017-08-12
      • 2014-12-07
      • 1970-01-01
      • 2014-01-20
      • 2012-07-10
      相关资源
      最近更新 更多