Java/Scala - How to get the path to your Jar file

Last week I ran into a situation where I was bundling a Java/Scala application on a Mac OS X system, which (as usual) requires you to bundle your code in a Jar file. I was working with the jnativehook library, where I saw some code like this:

String path = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath().toURI());

That code actually comes from this SO link, but the jnativehook code was very similar.

In short, this code lets you determine the path to the Jar file that your Java code is running in. I don’t know how often you need something like this, but I thought it was pretty cool. (I thought I might need code like this in a new version of my Sarah application, but I found a better way to get what I wanted.)

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.