This is an old revision of the document!


Using Resources in Java Programs

Overview

One commonly wants to use icons, configuration files, and other kinds of resources in Java programs. While there are many ways to do accomplish, doing it in a way that is portable requires some thought because of the way different IDEs and deployment mechanisms (e.g., .jar files ) organize code.

Icons

To easiest way to refer to icons in a protable fashion is to use a URL object (from the java.net package), and the easiest way to get the appropriate URL object is to use a Class object. For example, if you want to get the URL for a resource named logo.png that is in the icons directory under the top-level directory containing the class of the object referred to by this then you would do the following:

URL url = this.getClass().getResource("/images/logo.png").

You could then load it as follows:

ImageIcon icon = new ImageIcon(url);

Resource Bundles

The static getBundle() method in the ResourceBundle class can be passed a ClassLoader that it will use to locate the resources. For example, if you want to get the ResourceBundle with the prefix Strings that is in the top-level directory containing the class of the object referred to by this then you would do the following:

ResourceBundle strings;
strings = ResourceBundle.getBundle("Strings", Locale.getDefault(), this.getClass().getClassLoader());

Other Kinds of Resources

For other kinds of resources (e.g., configuration files), the easiest way to ensure that your code is portable is to use an InputStream object (from the java.io package) to refer to the resource and use a Class object to retrieve the appropriate InputStream object.

For example, if you want to get the InputStream for a text resource named default.cfg that is in the configurations directory under the top-level directory containing the class of the object referred to by this then you would do the following:

InputStream is = this.getClass().getResource("/configurations/config.txt").

You could then read the first line of this text resource as follows:

BufferedReader in = new BufferedReader(new InputStreamReader(is));
String   line = in.readLine();

Under the Hood

These technique uses the ClassLoader infrastructure to retrieve resources from the .jar file. So, it is very important that you understand the relative locations of the resource and the object that you call getClass() on. A leading / will start at the root of the directory tree, but you still must understand where in the .jar file is the root. Omitting the leading /, on the other hand, will start at the location of the .class file of the object referred to by this.