[an error occurred while processing this directive]
Domain for sale!
Start Search Contents Index Links About

Load resources

Find external resource files

2007 - Week 12 - Havard Rast Blok

When loading images, data files and other external resource files for an application, some path often has to be specified. It is then most useful to specify a relative path, and search for the file dynamically in runtime. These small example shows how to build in a little redundancy when loading files.

Often when working in Eclipse, I find that the root project folder is not the same as the root class path folder. Or the project is called something else on my laptop. This might cause a problem if you use the Java ClassLoader to load resources, and are to busy to mess around with the classpath. A convenient way to still get a URL for your resource which might be located on the local file system instead of a JAR, might be:

File file = new File(name);
if(file.exists()) {
    url = file.toURI().toURL();
}

If the simple file check fails, and the resource cannot be loaded from the current path, we might move on to try the ClassLoader. And if a File object is required, it can be retrieved from the path:

ClassLoader cl = getClass().getClassLoader();
URL url = cl.getResource(name);
if(url != null) {
    file = new File( url.getFile() );
}

Finally, an example application combining these two techniques is presented. Usage examples and output follow:

> ls GetResource.*
GetResource.class  GetResource.java

> java GetResource GetResource.java
Resource name:  GetResource.java
File:           GetResource.java
URL:            file:.../GetResource.java
> java GetResource java/io/File.class
Resource name:  java/io/File.class
File:           file:/usr/java/jdk1.6.0/jre/lib/rt.jar!/java/io/File.class
URL:            jar:file:/usr/java/jdk1.6.0/jre/lib/rt.jar!/java/io/File.class


GetResource.java



site: Håvard Rast Blok
mail:
updated: 16 July 2010