FAQ

Java

JSP

Servlet


Advertisement



What is different between ClassLoader.getResourceAsStream() and Class.getResourceAsStream()?

A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code. According to API document:

The ClassLoader.getResourceAsStream(name) returns an Inputstream for reading the specified resource or null if the resource could not be found. The name of a resource is a '/'-seperated path name that identifies the resource. The name no leading '/' (all namea are absolute).

The Class.getResourceAsStream(name) returns an Inputstream for a resource with a given name or null if no resource with the given name is found. The name of a resource is a '/'-seperated path name that identifies the resource. If the name with a leading "/" indicates the absolute name of the resource is the portion of the name following the '/'. All other names are relative to the class's package, 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 '.'.

In Class.getResourceAsStream(name), the rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream(java.lang.String).

For example, watch the leading slash:

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


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |