Discussions

General J2EE: getClassLoader().getResourceAsStream && .getResourceAsStream()

  1. Hi,

    We can laod a particular resource(properties file, config files etc) as InputStream in two ways...
    Suppose TestClassLoader is our class where we load our resource...

    1.) TestClassLoader.class.getResourceAsStream("com/somepacakage/props.properties");

    2.) TestClassLoader.class.getClassLoader().getResourceAsStream("com/somepacakage/props.properties");

    -- Whats is the difference between above two approaches?
    -- Which should be used when?

    Thanks,
    Jay Khimani
  2. I don't think there any different. If you look at the implementation of Class.getResourceAsStream(), it delegates this call to the underlying class loader.
  3. subtle differences[ Go to top ]

    Javaworld has a decent article on this subject which points out a subtle difference in how resource should be referenced in the classpath/package structure.
    http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html

    according to this article it is important to note the leading slash when calling getResourceAsStream() on the Class class.

    ClassLoader.getResourceAsStream("some/pkg/resource.properties");
    Class.getResourceAsStream ("/some/pkg/resource.properties");