getResourceAsStream

You think that java.lang.Class.getResource(String name) is the same as java.lang.ClassLoader.getResource(String name) ? Think again…

The javadoc for java.lang.Class.getResource(String name) states that:

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

  • If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
  • Otherwise, the absolute name is of the following form: modified_package_name/name where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

Now compare this with the javadoc for java.lang.ClassLoader.getResource(String name) :

The name of a resource is a ‘/‘-separated path name that identifies the resource

Yes, this means that when using ClassLoader.getResource(String name), the path must NOT start with a ‘/’, and in the end, these 2 statements are similar:

this.getClass().getResource("/sub/file1.properties");

// note that there is no '/':

this.getClass().getClassLoader().getResource("sub/file2.properties");

Laurent KUBASKI

Advertisements

About lkubaski
www.kubaski.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: