java resource access

Jar

<Class>.getResourceAsStream

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)
This method accepts the name of the resource as a parameter and returns an InputStream reference for the resource (or null if it cannot find the resource).
The name provided to the getResourceAsStream method can be an absolute or relative pathname. If relative, it is interpreted relative to location of the class.

The rules for searching resources associated with a given class are implemented by the defining class loader of the class.

This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResourceAsStream.

For example:

Type          Path                    Actual Location ( / is package root)
Absolute    /sample.propertie       /sample.properties
Relative    sample.properties       /path/of/package/sample.properties

<ClassLoader>.getResourceAsStream

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ClassLoader.html#getResourceAsStream(java.lang.String)

Finds the resource with the given name. 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.

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

This method will first search the parent class loader for the resource; if the parent is null the path of the class loader built-in to the virtual machine is searched. That failing, this method will invoke findResource(String) to find the resource.

It only supports absolute paths. Is this right?

Tomcat WebApp Classloader

http://www.mbaworld.com/docs/class-loader-howto.html
The search path (for resources) used by ClassLoader is:

/WEB-INF/classes of your web application
/WEB-INF/lib/*.jar of your web application

So you can put resources into WEB-INF/classes or your jar file.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License