Recently I came accross very strange behaviour of getResourceAsStream method.
I have an application that I developed on Windows. This app is a desktop application based on OSGI framework. I created a bundle, set up needed packages and added some data files to those packages so that they are contained within the jar file.
I load the data using that:
this.getClass().getResourceAsStream("pl/com/myapp/resource.dat");
It worked great both in eclipse and when I deployed my application and run it on the system outside IDE.
I then moved the development to ubuntu 12.04. An to my surprise the method mentioned above always returns null. The data is where it should be. All the settings look OK. No absolute paths in any config files.
I tried many different things. I altered the path to:
this.getClass().getResourceAsStream("/pl/com/myapp/resource.dat");
I tried not to contain the package root but insert a path that is relative to the class location (lets assume that my class is: pl.com.myapp.MyClass):
this.getClass().getResourceAsStream("resource.dat");
I also tried:
this.getClass().getResourceAsStream("./resource.dat");
But nothing worked :(
But when I create a simple Java application everything works smoothly and the method returns the proper stream.
Did anyone come accross such problems ?
I use eclipse-juno on ubuntu 12.04.
You should always close streams (and any other Closeable, actually), no matter how they were given to you. Note that since Java 7, the preferred method to handle closing any resource is definitely the try-with-resources construct.
getResourceAsStream , send the absolute path from package root, but omitting the first / . If you use Class. getResourceAsStream , send either a path relative the the current Class object (and the method will take the package into account), or send the absolute path from package root, starting with a / .
Class getResource() method in Java with ExamplesThe method returns the specified resource of this class in the form of URL object. Parameter: This method accepts a parameter resourceName which is the resource to get. Return Value: This method returns the specified resource of this class in the form of URL objects.
Be careful at the case sensitivity as Linux paths are case sensitive, compared to the Windows ones.
Just a guess, but is it possible that this.getClass()
is not the class you think it is? For example if somebody subclasses you then this.getClass()
will return the subclass rather than your baseclass, which may be in another bundle and therefore won't have visibility of the resource.
When doing these kind of resource lookups you should always use the literal class name, e.g.: MyClass.class.getResourceAsStream()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With