I don't seem capable to remember some of the most basic things in Java at times. I guess it's because I do them so rarely that I have time to forget until next time.The other day it was how to define the path for the getResourceAsStream() method. This time I'm going to blog it so I can find the instructions next time I end up not remembering.
I need to read the image named image.jpg located at the absolute build path /Users/tomasmalmsten/code/myproject/src/main/resources/image.jpg. I am using Maven2 so the final location before packaging is /Users/tomasmalmsten/code/myproject/target/classes/image.jpg. And when it's been packaged it will be in the classes/image.jpg location of the jar file. What I can't remember is how to create the path so that it can be found by the class loader when using getResourceAsStream().
The trick is to use a / in the beginning of the search path. This denotes that the class loader should start looking at the root, which in the case with image.jpg is where it is. So the path for image.jpg is /image.jpg.