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("");
// absolute to classpath
URL url = Class.getResource("/gigadot/exp/");
// relative to path of Class's package
InputStream ins = Class.getResourceAsStream("");
// absolute to classpath
InputStream ins = Class.getResourceAsStream("/gigadot/exp/");
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/");
InputStream ins = ClassLoader.getResourceAsStream("gigadot/exp/");

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.

// 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 :

No comments:

Post a Comment