RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
May 1, 1999

Loading Resources With the getResource() Method

Most nontrivial applications are packaged with "resource files," which are nothing more than files used by the application for various purposes. Some examples of these resources include image (GIF, JPEG) files, message/text data, configuration/initialization information, and so on. There are several of ways to read these resources, but most of them are closely tied to the way in which the code is packaged. For example, one way will work correctly for a Java application, while another will work only for an applet. Obviously, the most desirable approach is to use a mechanism that functions correctly regardless of the packaging of the code. This is where the getResource() method in java.lang.Class is useful. It returns a URL that represents a resource, which can then be used to read the resource.

In this example, the resource stored in "myimage.gif" is loaded and drawn at the upper left corner of the screen. Note that this code will work regardless of whether or not it is run as an application, an applet, or is included in a Java Archive (JAR) file. For more information, read Accessing Resource in a Location-Independent Manner, which is included in Sun's documentation provided with the Java Development Kit (JDK).

import java.awt.*;
import java.net.*;
public class ResourceTest extends Frame {

	Image img;

	public ResourceTest() throws Exception {
		URL myurl = this.getClass().getResource("/myimage.gif");
		Toolkit tk = this.getToolkit();
		img = tk.getImage(myurl);
	}  //  public ResourceTest()

	public void paint(Graphics g) {
		g.drawImage(img, 0, 0, this);
	}  //  public void paint()

}  //  public class ResourceTest extends Frame
Brett Spell
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date