views:

115

answers:

5

My Project Setup

I have the following project setup:

\program.jar  
\images\logo.png

In my code, I reference the image with the relative URL "images/logo.png".

Problem

If I run this program with the following command while in the directory:

c:\projects\program_dir\bin\>java -jar program.jar

Then everything works and Java is able to locate the image.

Now, my problem is, that I need to be able to run the program from a different directory.

c:\>java -jar c:\projects\program_dir\bin\program.jar

The program is executed, but now all the relative URLs no longer work.

What I need

How do I calculate the execution home of the program.jar file, so that I can change my relative URLs into absolute URLs?

+8  A: 

What I would do, if possible, is package your images in with your Jar.

That way you don't have to worry about where your Jar is launched from.

You would then need to load images similar to the following:

InputStream stream = this.getClass().getClassLoader().
                                     getResourceAsStream("/images/logo.png");
jjnguy
+1 Leverage classpath for loading static resources. See also: http://stackoverflow.com/questions/861500/url-to-load-resources-from-the-classpath-in-java, http://stackoverflow.com/questions/3294196/load-resource-from-anywhere-in-classpath, http://stackoverflow.com/questions/1900154/classpath-resource-within-jar
unhillbilly
A: 

Resources have to be in the class path(s). You may try one of these:

  1. Placing the images into the program.jar.
  2. Like most of the programs, they have a APP_HOME directory, e.g. MAVEN_HOME, register that and refer to your files as File instead - $APP_HOME/the-file.ext (with System.getenv()).
yclian
+1  A: 

You should really include your resources in your JAR.

Failing that, you can parse the absolute path out of the Main class resource. Assuming your Main class is actually called "Main":

Main.class.getResource("Main.class").getPath();
Karl Johansson
A: 

As Nelson mentioned, package them with your JAR (just copy them alongside your .class files), then you can find them via a simple this.getClass().getClassLoder().getResource("images/foo.png").

Tassos Bassoukos
A: 

You need to add a parameter which describes your class path. Should look something like

java -cp c:\projects\program_dir\bin -jar program.jar

this will put your jar and image on the class path and it will load successfully.

eugener