问题
I'm trying to get load an image from my jar. But no matter what string I supply for getResource() it always returns null.
try {
System.out.println(Bootstrapper.class.getResource("./img/logo.png").toURI().getPath());
} catch (URISyntaxException ex) {
Logger.getLogger(CrawlerFrame.class.getName()).log(Level.SEVERE, null, ex);
}
ImageIcon ii = new ImageIcon(Bootstrapper.class.getResource("./img/logo.png"));
setIconImage(ii.getImage());
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at net.sharpcode.crawler.ui.CrawlerFrame.init(CrawlerFrame.java:35) at net.sharpcode.crawler.ui.CrawlerFrame.(CrawlerFrame.java:28) at net.sharpcode.crawler.Bootstrapper$1.run(Bootstrapper.java:55)

I've tried:
getResource("")
getResource(".")
getResource("./")
getResource("/img/logo.png")
Bootstrapper.class.getProtectionDomain().getCodeSource().getLocation().getPath()
回答1:
this.getClass().getResource("/net/sharpcode/crawler/img/logo.png")
回答2:
Get rid of the "./" part - just use:
Bootstrapper.class.getResource("img/logo.png");
... that's if it's relative to Bootstrapper.class
. If the img
"directory" is in the root of the jar file, use
Bootstrapper.class.getResource("/img/logo.png");
回答3:
From the stack trace I see the Bootstrapper
class lies in net.sharpcode.crawler
package. It means the following path ./img/logo.png
will be resolved to /net/sharpcode/crawler/img/logo.png
. I guess /img
is a top level directory, so either use absolute path:
Bootstrapper.class.getResource("/img/logo.png")
or load via ClassLoader
:
Bootstrapper.class.getClassLoader().getResource("img/logo.png")
来源:https://stackoverflow.com/questions/10163012/jar-get-image-as-resource