Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Loading resources from the file system

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?

like image 772
JesperGJensen Avatar asked Jan 26 '26 11:01

JesperGJensen


2 Answers

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");
like image 64
jjnguy Avatar answered Jan 28 '26 01:01

jjnguy


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();
like image 40
Karl Johansson Avatar answered Jan 28 '26 01:01

Karl Johansson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!