Using resources in a java program

Setting the correct path for resources in a Java program so that they both work from command line and from inside a jar can be confusing and daunting. We show a simple, step by step working example, which uses both available syntaxes (i.e. by calling the ClassLoader or not).

We will assume that we have the following development path:

src
 |- sample
       |- UsingResources.java
       |- res
           |- file.txt

This is our java class:

package sample;
public class UsingResources {
    public static void main(String a[]) {
        new UsingResources();
    }
    UsingResources() {
        ClassLoader cl = this.getClass().getClassLoader();
        System.out.println(cl.getResource("sample/res/file.txt"));
        System.out.println(getClass().getResource("res/file.txt")); 
    } 
} 

As we can see,

  • the getClass().getClassLoader().getResource() method  requires the path specification starting from the directory which contains the package (src),
  • the getClass().getResource() method requires a path relative to the class location (src/sample)

we can test by compiling the code:

cd (full-path-to/)src
javac sample/UsingResources.java
java sample/UsingResources

and the output will be

file:/Users/ronchet/DemoResources/src/sample/res/file.txt
file:/Users/ronchet/DemoResources/src/sample/res/file.txt

showing that everything works.

Now let us try with the jar. First, let us create it:

echo "Main-Class: sample/UsingResources" > MainClass.txt
jar cmf MainClass.txt UsingResources.jar sample/*.class sample/res/*

Let’s run it:

java -jar UsingResources.jar

the output is

jar:file:/Users/ronchet/DemoResources/src/UsingResources.jar!/sample/res/file.txt
jar:file:/Users/ronchet/DemoResources/src/UsingResources.jar!/sample/res/file.txt

showing that everything works correctly.

Advertisements
Tagged with:
Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: