NullPointerException when using path name to load

2019-05-07 19:58发布

问题:

Looked everywhere and still can't find a solution to this problem while using NetBeans.

When I use the following code to load a file by path:

Image owl = new ImageIcon(this.getClass().getResource("/images/owl.gif")).getImage();

I get a NullPointerException. I read somewhere where it suggested creating a new folder and making it a source file for the project, but that didn't help. I've tried multiple suggestions that I found on this site and others, but I'm not getting any results.

I'm starting to wonder if there is something wrong with the way that I am putting the path in, but I'm doing it exactly the way that it shows everywhere else. I've tried every combination of every example that I could find to solve this problem for the last couple of days, but nothing is working.

回答1:

It seems like the images folder wasn't part of your classpath. In Eclipse, it's not in what they call the Build Path.

Right-click on the images folder, select Build Path and Use as Source Folder. The folder will now be added to the classpath whenever you run your application through Eclipse. If you do this, you need to change your path to

Image owl = new ImageIcon(this.getClass().getResource("/owl.gif")).getImage();

because now everything in images will be put directly on the classpath.

You could instead, make a package called images under your normal src folder and call it as

Image owl = new ImageIcon(this.getClass().getResource("/images/owl.gif")).getImage();


回答2:

.getResource() returns null when it cannot find the resource. That's where you're getting the null.

Your problem is that the path for owl.gif is incorrect.