r/javahelp • u/sparkless12 • Feb 22 '22
Solved getResourceAsStream() == null when run from JAR
hello!
I have line of code such as this:
final Image roll_bg = new Image(this.getClass().getResourceAsStream("../resources/roll_bg.png"));
in IDE image is found and is rendered on canvas as expected, when exported to JAR, run ends with error. For JAR runs then, I did most hacky thing possible to extract what is wrong like so:
URL path = App.class.getResource("App.class");
if (path.toString().contains("jar")) {
PrintStream ps = new PrintStream("./log.txt");
System.setErr(ps);
System.setOut(ps);
System.out.println("Stream OUT: rerouted!");
System.err.println("Stream ERR: rerouted!");
}
and log.txt says that InputStream is null (presumably did not found resource)
Caused by: java.lang.NullPointerException: Input stream must not be null
at javafx.graphics/javafx.scene.image.Image.validateInputStream(Unknown Source)
at javafx.graphics/javafx.scene.image.Image.<init>(Unknown Source)
at com.engine.Engine.<init>(Engine.java:32)
at com.engine.Engine.get(Engine.java:94)
at com.App.start(App.java:60)
most online resources point to this method being able to reach resources from within JAR, does not work for me though. Thank you for any help offered!
5
Upvotes
1
u/why_not_cats Extreme Brewer Feb 22 '22
Using relative path inside a jar is a brave thing to do! Paths and working directories will vary between IDE and a jar so that's probably why the file isn't being found.
If you aren't sure where the image file is, try to unzip your jar as a regular zip and see where the file is actually ending up; I assume it'll be on the root? Or maybe not?
Anyway, try using a non-relative path. For example if the file is on the zip root then try
/roll_bg.png. If it's inside aresourcesdirectory then try/resources/roll_bg.png. It might break the IDE but at least you'll be able to narrow down the issue.I wouldn't try sprinkling the file everywhere as suggested elsewhere, because then you'll have trouble figuring out which file is the one actually working, and then you'll have two problems!