Saturday, 16 October 2010

Loading classpath resources

There are several options to load resources from classpath. I want to note down for reference.

Using Class.getResource method
The name of resource is relative to Class's package unless it leads with "/". The leading "/" indicates absolute path (absolute relative to classpath).

// relative to path of Class's package
URL url = Class.getResource("resource.properties");
// absolute to classpath
URL url = Class.getResource("/gigadot/exp/resource.properties");
// relative to path of Class's package
InputStream ins = Class.getResourceAsStream("resource.properties");
// absolute to classpath
InputStream ins = Class.getResourceAsStream("/gigadot/exp/resource.properties");
Given relative resource path is usually a preferred method. It is easier when you perform refactoring.

Using ClassLoader.getResource method
The name of resource is always absolute to classpath and leading "/" is not allowed.

URL url = ClassLoader.getResource("gigadot/exp/resource.properties");
InputStream ins = ClassLoader.getResourceAsStream("gigadot/exp/resource.properties");

Caution :
If you choose to get URL object of your resource, the path given by URL.toString() is an encoded URL string. It must be decoded if you want to use as path for File object. This is because some characters, which is valid in path name, has to be encoded for URL, e.g. space bar character is encoded to %20.

// resource at "C:\Program Files\file.txt"
File file = new File(url.toString()); // not found
File file = new File(URLDecode.decode(url.toString(), "UTF-8")); // found

Above example has not been test for more complicated resource path, e.g already containing encoded URL.

Alternatively,
// resource at "C:\Program Files\file.txt"
File file = new File(url.toURI());

The constructor of File class supports and automatically decodes the file: protocol.

More details can be found at :
http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html

No comments:

Post a Comment