0

I tried to create an InputStream pointing at an .ico file, which is in a directory in the src directory. I also create an InputStream for a different jar file in my src.

InputStream inIco = Installer.class.getResourceAsStream("/res/" + iconName + ".ico");
InputStream inApp = Installer.class.getResourceAsStream("/res/" + applicationName + ".jar");

that is how I tried to load it. The inputstream for the jar file works, but the other one is null.

Edit: Sorry for the confusion guys. I didnt build the jar, I just ran it from my editor, wich obviously gives me different results, now it is working. Thanks for your answers.

carlos.gmz
  • 108
  • 7
  • Can you show us your stack trace as well as your folder structure? In Java the file type does not matter so if it works for one of your files it should also work for your icon – David Brossard Jan 25 '21 at 23:41
  • Though now that I'm looking at your code I realize what might be wrong: you are using the class loader. A jar file is likely automatically loaded but an icon wouldn't. Make sure you add the icon to your class path – David Brossard Jan 25 '21 at 23:42

1 Answers1

0

getResourceAsStream (gRAS) loads from the same place java loads class files. That's great - it means you can ship your app as a jar and put these resources inside. If it's not working for you, you've misconfigured your build. Specifically, java is first going to determine the classpath root of your Installer.class file and looks there. If you're not sure what that is, run this code:

System.out.println(Installer.class.getResource("Installer.class"));

which will print something like jar:file:/Users/carlos/projects/FooBar/dist/foobar.jar!com/foo/Installer.class

and this tells you that gRAS is going to look in that foobar.jar file.

From there, the resource is loaded relatively to the root (because of that leading slash): Within that jar, it will look for /res/app.ico. Without it, it loads relative to the same dir/package of Installer class (in this example above, gRAS("hello.txt") is the same as gRAS("/com/foo/hello.txt").

To make this work out, your build system is responsible. For maven and gradle, have src/main/java/com/foo/Installer.java along with src/main/resources/res/icon.ico and all should be well. If this is not working out, explain how you've set up your environment because something is misconfigured if this isn't working. If you're using another build tool (such as perhaps ant, sbt, or relying on your IDE to take care of it), name the tool and perhaps we can help address the misconfiguration.

rzwitserloot
  • 44,252
  • 4
  • 27
  • 37