HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"Fun with Resources and Class Loaders"
Vol. 2, Issue 5, p. 41

	

Listing 1: Loading any resource from the local system requires 1) getting a URL
using getSystemResource(); and 2) getting the content of the URL.

…
try {
    URL urlImage = ClassLoader.getSystemResource(“Example.gif”);
    Image img = urlImage.getContent();
} catch (NullPointerException npe) {
    // No such resource found in the classpath…
} catch (IOException ioe) {
    // problem reading from the file, but file was found.
}
…

Listing 2: Loading a resource from a ClassLoader, such as in an applet context, 
uses pretty much the same two steps as in Listing 1, but using different method calls.

…
try {
    ClassLoader appletCL = getClass().getClassLoader();
    URL urlImage = appletCL.getResource(“Example.gif”);
    Image img = urlImage.getContent();
} catch (NullPointerException npe) {
    // Either local class’ classl loader is the System class loader,
    // or the image resource could not be found by the applet class loader.
} catch (IOException ioe) {
    // problem reading the resource
}
…

Listing 3: The PackageResources class is a utility class with a single static method: 
getPackageResource(). This method is made to work in either an application or an applet context.

public class PackageResources {
    public static Object getPackageResource(String strResource, Class refClass) {
        ClassLoader cl = refClass.getClassLoader();

        String strPackageName = refClass.getName();
        int i = strPackageName.lastIndexOf(‘.’);
        if(i == -1)
            strPackageName = “”;
        else
            strPackageName = strPackageName.substring(i);

        String str = (strPackageName.length()>0 ? strPackageName + “/” : “”) + strResource;

        if(null == cl)
            return ClassLoader.getSystemResource(str);
        return cl.getResource(str);
    }
}

Listing 4: This code snippet shows how you would use the getPackageResource() method 
in Listing 3 to load an image.

…
Image img = PackageResources.getPackageResource(“Example.gif”, getClass());
…


 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: info@sys-con.com

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.