Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
697 views
in Technique[技术] by (71.8m points)

image - Java ImageIO.read(getClass().getResource()) returns null

The line

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

fails with

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

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

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

and

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

will look for the resource in

/view/random/name/gate_and.png

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

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

You can access it with

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

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

All these rules are explained in the javadoc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...