Java ImageIO.read(getClass()。getResource())返回null [英] Java ImageIO.read(getClass().getResource()) returns null

查看:222
本文介绍了Java ImageIO.read(getClass()。getResource())返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

失败,

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

我正在使用Eclipse,在bin文件夹下的导航视图中有文件gate_and.png ,表明该文件位于构建路径中。

I'm using Eclipse and in the navigation view under the bin folder there is the file gate_and.png, suggesting that the file is in the build path.

在包浏览器视图中,我有

In the package explorer view I have

项目/ src / view / class - 这是具有上述代码的类。

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

项目/图像/gate_and.png

project/images/gate_and.png

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

I right clicked the project folder > build path > link source to add the images folder as a source, doing this again provides a confirmation msg that says images is already in the source.

我也尝试将gate_and.png更改为images / gate_and.png和/images/gate_and.png,但是因为图像gate_and.png在bin文件夹中,我认为原文是正确的。

I have also tried changing gate_and.png to images/gate_and.png and /images/gate_and.png, but since the image gate_and.png is in the bin folder, I think the original is correct.

我对此很新,我看过类似的问题在这里问了很多但没有给了我一个解决方案。

I'm fairly new to this and I've looked at similar questions asked a lot on here but none have provided me with a solution.

提前感谢您的任何帮助。

Thanks in advance for any help.

Matt

推荐答案

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

Assuming your class is in package view.random.name, then

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

将在

/view/random/name/gate_and.png

相对于类路径的根。你显然没有那个名字的资源。

relative to the root of the classpath. You apparently don't have a resource by that name there.

通过设置项目/图像作为构建路径入口,Eclipse将在类路径中包含其中的所有内容。因此,您的资源将显示在

By setting project/images as a build path entry, Eclipse will include everything in it on the classpath. Therefore, your resource will appear at

/gate_and.png

您可以使用

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

注意领先 / 这意味着开始查看类路径的根,即。这是绝对的路径。

Note the leading / that means start looking at the root of the classpath, ie. it's an absolute path.

所有这些规则都在 javadoc

这篇关于Java ImageIO.read(getClass()。getResource())返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆