0

I developed a little program a while back, which I made into an executable jar-File. It used some images I placed in a separate folder called "cache", which is always in the same directory as the .jar.

consoleBG = ImageIO.read(new File("./cache/consoleBG.png").toURI().toURL());

Back then it worked out of Netbeans and from the jar-file.

Now I have to come back to this project and suddenly the jar no longer uses a relative path:

java.io.FileNotFoundException: C:\Users\Dromlius\.\cache\consoleBG.png

I tried everything and the solution I found online:

MyClass.class.getResource("cache/consoleBG.png").toUri()

results in a NullPointerException!

I just need a quick and dirty way to get the relative path to the .jar-file, because the software will be used on many different systems.

Thank you in advance,

Dromlius

EDIT: Ok, when I call the jar from console like: C:\Users\Dromlius>java -jar X:\Dromlius\Projects\MyProgram.jar it does not work! But if I navigate to the folder X:\Dromlius\Projects first, it works.i I don't know why, but it is enough for my purpose. I'm going to leave this question open for a bit though because someone might have similar problems and can not use this workaround.

Dromlius
  • 17
  • 5
  • did you try, MyClass.class.getClassLoader().getResource("cache/consoleBG.png").toUri() ? – rudedude Apr 11 '16 at 09:23
  • see another related question at SO, [How to Load File Outside of, but Relative to, the JAR?](http://stackoverflow.com/questions/5097789/how-to-load-file-outside-of-but-relative-to-the-jar) – Sabir Khan Apr 11 '16 at 09:26

1 Answers1

0

You can use ClassLoader.getSystemResource("cache/consoleBG.png").toURI() and make sure that . (Current Directory) is in class-path

Sanjeev
  • 9,876
  • 2
  • 22
  • 33
  • `ClassLoader.getSystemResource("cache/consoleBG.png")` returns null. What am I missing? the jar is in the same folder as my cache folder. And I checked spelling 1000 times! – Dromlius Apr 11 '16 at 09:34
  • You need to add current directory "." to your classpath – Sanjeev Apr 11 '16 at 09:48