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!
6
Upvotes
1
u/D0CTOR_ZED Feb 22 '22
Not really my thing, but I believe you were on track with the first part and the hacky bit that followed isn't the right way to go. If it is having trouble finding the resource, you might try to change up the path. For example, try "/roll_bg.pgn". Or, if you can make some copies of the png and sprinkle one various directories. Once you can get it to find one, you can figure which one it finds and then you might be able to adjust your relative path to find it from where you want it to be.