Use ClassLoader to load resources

To load images in applications (and any other resources), do not use absolute paths. You cannot know where the user will install the application or will he start it in the application root directory. Instead, use the ClassLoader to find a resource on the class path (this also works when resources are packaged in JAR archives).

    URL u= ClassLoader.getSystemResource(relativePath);
    ImageIcon i = new ImageIcon(u);

For greater flexibility, don’t use the system ClassLoader, but getClass().getClassLoader() or (in static methods) Thread.getCurrentClassLoader(). This is important in environments with a hierarchy of class loaders (for example, in Tomcat or JBoss applications).

Best Practices

A good advice for loading resources using a ClassLoader is by creating a class that may be named ResourceManager that does all the ClassLoader stuff. This could then provide methods for loading resources like this:

package org.whatever.foo;
 
import java....;
 
public class ResourceManager {
  protected static final ResourceManager INSTANCE         = new ResourceManager();
 
  protected static final String          RESOURCE_PACKAGE = "org/whatever/foo/resources/";
 
  protected ResourceBundle               bundle;
 
  public static final ResourceManager getInstance() {
    return INSTANCE;
  }
 
  private ResourceManager() {
    this.bundle = ResourceBundle.getBundle(RESOURCE_PACKAGE + "Resources");
  }
 
  public InputStream getResourceStream(String file) {
    return this.getClass().getClassLoader().getResourceAsStream(RESOURCE_PACKAGE + file);
  }
 
  public String getText(String key) {
    return this.bundle.getString(key);
  }
  public String getText(String key, Object args[]) {
    return MessageFormat.format(this.bundle.getString(key), args);
  }
  public String getText(String key, Object arg1) {
    return MessageFormat.format(this.bundle.getString(key), new Object[] {arg1});
  }
  public String getText(String key, Object arg1, Object arg2) {
    return MessageFormat.format(this.bundle.getString(key), new Object[] {arg1, arg2});
  }
}

It could also provide convenience methods for loading images, etc.

 

Comments? Corrections? Contact us or Login to edit pages directly (registration is free and takes less than displaying a JLabel)
  best/use_classloader_for_resources.txt · Last modified: 2006/10/19 17:26 by 84.61.175.253 (chbeer)
 
Recent changes | RSS changes | Table of contents | News Archive | Terms And Conditions | Register