5

I need to load a file outside of the JAR, but relative to it (lib/config/config.ini to be exact). I used that exact path, and it works fine as long as the working directory is where the JAR is, i.e.

/path/to/jar$ java -jar JAR.jar

If it's run like this:

~$ java -jar /path/to/jar/JAR.jar

It can't find it. How can I correctly load a file relative to the location of the JAR?

Jonah
  • 9,991
  • 5
  • 45
  • 79
  • possible duplicate of [Loading a file relative to the executing jar file](http://stackoverflow.com/questions/3627426/loading-a-file-relative-to-the-executing-jar-file) – Sean Patrick Floyd Feb 23 '11 at 22:11
  • 1
    Check this out: http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file – iluxa Feb 23 '11 at 22:12
  • @iluxa: thanks, that works. Strange that it's so hard to load a relative path... – Jonah Feb 23 '11 at 22:26
  • @Sean: I couldn't get that one working. – Jonah Feb 23 '11 at 22:35
  • "Strange that it's so hard to load a relative path..." Oracle considers the path of the Jar to be **not the business** of the application itself. Neither applets nor JWS apps. would have the slightest chance of finding the installation path. – Andrew Thompson Feb 24 '11 at 02:56

1 Answers1

3

Try using getClassLoader().getResource("classname") to find the URL of a class in your jar file. You'll find it's delimited with a ! between the path to the jar, and the path within a jar, which you can easily slice.

ConcurrentHashMap
  • 4,998
  • 7
  • 44
  • 53
Chris Nash
  • 2,941
  • 19
  • 22