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:

 |- sample
       |- 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();

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/
java sample/UsingResources

and the output will be


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


showing that everything works correctly.

Tagged with:
Posted in Uncategorized

Leave a Reply

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

You are commenting using your 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: