Reading a Resource From a Jar File

There are times when it can be convenient for static files (such as text files, configuration files, images, etc.) to be packaged with a library. In the Java world, these types of files are referred to as resources and the libraries are known as jar files. The simplest way to ensure that a jar file can reference the resources it needs is to physically bundle them into the jar file itself.

The question then becomes: How can the code within a jar file reference a resource file?

Reading a Resource File

It's actually pretty simple, as illustrated in Listing 1. Java provides several ways to read a resource file, of which the simplest is to use the getResourceAsStream method provided by Java's Class class. This method accepts the name of the resource as a parameter and returns an InputStream reference for the resource (or null if it cannot find the resource). Content can be easily read from the file using a BufferedReader object.

The name provided to the getResourceAsStream method can be an absolute or relative pathname. If relative, it is interpreted relative to the package path. For example:

Type Path Expected Location
  Absolute /myapp.properties /myapp.properties
  Relative myapp.properties /com/keenertech/experiment/myapp.properties

The leading "/" causes the getResourceAsStream method to look for the resource at the top level within the jar file. With the relative pathname, the file is expected to be located at the same level within the jar file as the class itself.

Note that the ClassLoader class also has a getResourceAsStream method which can be used to read resources, but it only supports absolute paths. In general, the Class version of the method is more frequently used.

Listing 1 - Displaying A Resource File

package com.keenertech.experiment;

import java.io.*;
import java.util.*;

public class ResourceExperiment
{ 
   private void displayResource(String strName)
   {
      try
      {
         BufferedReader objBin = new BufferedReader(new InputStreamReader(
            this.getClass().getResourceAsStream(strName)));
         if (objBin != null)
         {
            String strLine = null;
            while ((strLine = objBin.readLine()) != null)
            {
               System.out.println(strLine);
            }
            objBin.close();
         }
         else
         {
            System.out.println("Error: Unable to retrieve InputStream");
         }
      }
      catch (Exception e)
      {
         System.out.println(e);
      }
   } // End Method

   public static void main(String[] args)
   {
      ResourceExperiment objRes = new ResourceExperiment();
      objRes.displayResource("/myapp.properties");
   } // End Method

 } // End Class

Reading a Properties File

Well, that was a great way to read, and display, a resource file, but it would be nice to actually use the properties defined in the myapp.properties file. Listing 2 shows how the properties can easily be processed from a configuration file packaged as a resource. This technique can be a great way to set default parameters for a class.

Listing 2 - Reading Properties From a Resource File

 private void readPropertyFile(String fileName)
 {
    try
    {
       Properties objProperties = new Properties();
       objProperties.load(this.getClass().getResourceAsStream(fileName));

       strHostName = objProperties.getProperty("hostname");
       // .....more properties as needed.....
    }
    catch (Exception e)
    {
       System.out.println("ERROR: Could not read properties file\n");
       e.printStackTrace();
    }
 } // End Method

To read the properties from the file, create an instance of the Properties class, then call the object's Load method with an InputStream that references the resource, as shown below:

   objProperties.load(this.getClass().getResourceAsStream(fileName));

To get a value for an individual property:

   strHostName = objProperties.getProperty("hostname");

Conclusion

In Java, static resources can safely and effectively be bundled with compiled classes within easily distributable jar files. Storing such resources within the jar files ensures that the resources will be available to classes when needed, i.e. — it is very difficult for the resources to become separated from the code when they are bundled with it. In turn, resources can be easily referenced by Java code, so there's no penalty, in terms of access cost, in bundling resources within jar files.



Comments

David Keener By RequiemOfLife on Tuesday, December 28, 2010 at 10:28 PM EST

Nice concise article, very helpful. Is there a way to write to a preference file as well?


David Keener By cd on Thursday, March 12, 2015 at 11:19 PM EST

java.lang.NullPointerException :(


David Keener By dkeener on Tuesday, March 17, 2015 at 12:41 AM EST

Eek. Hi "cd"... if I'm interpreting properly, it looks like you tried this, and it didn't work for you.

I can tell you that this code worked seven years ago when I wrote it. What I pasted into the article was actual live code. I can't currently tell you what may have changed in the Java world since then... I'm curious enough to take a run at the code again, but I can't promise you a timeframe.



Leave a Comment

Comments are moderated and will not appear on the site until reviewed.

(not displayed)