Finding the directory (folder) of a Java program’s running .jar file

by Market Tree

OK, so you have a computer program written in Java. You compile, build and package it. You have a directory (folder), perhaps named dist, which holds your Java archive .jar file together with other files. These other files could be one or more properties files, for example, which will allow the user to tweak certain properties of your program without needing a new .jar file.

The program user might run it using a link file or by typing a command directly from a command window. Either way, the command to run it might be of the form

java -jar [path/]YourProgram.jar

The problem
Your program needs to know in which directory your .jar file resides, in order to find another (properties or data?) file in the same folder. How to determine this folder, since it could be anywhere, and could change even between different runs?

A solution
Well, we have developed a nifty Java method which will allow this to be done easily. Its heart is a automagic line of code, and it is surrounded with some code to make this method easy-to-use and hopefully useful.

We set out the class file’s contents in full below. Copy, paste and enjoy?

package com.wordpress.markettree;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JarFolderFinder
  public JarFolderFinder()
  * Determine the path to the folder containing the .jar file used to run this
  * program. If a file name is supplied then append it to this path.
  * This method should only be called from a program running from its .jar file
  * (using the java -jar [[path to] file name].jar command),
  * otherwise the path returned is very likely to be invalid.
  * @param sFileName
  *   The file name to be appended to the path returned.
  *   If this is null or empty then nothing is appended.
  *   No check is made as to whether the file exists or not.
  * @return
  *   The path to the folder containing the .jar file used to run this program.
  *   If a file name is supplied then it is appended to this path.
  * @throws URISyntaxException
  public static Path constructPathToJarFolder(String sFileName)
   throws URISyntaxException
    Path pathResult = null;
    Path pathJar = null;
    // This is the magic line that yields the URL to the running .jar file
    URL url = JarFolderFinder.class.getProtectionDomain().getCodeSource()

    pathJar = Paths.get(url.toURI());
    Path pathJarFolder = pathJar;
    if (pathJar != null)
      int nNames = pathJar.getNameCount();
      if (nNames > 1)
        pathJarFolder = pathJar.getRoot();
        pathJarFolder = pathJarFolder.resolve(pathJar.subpath(0, nNames - 1));
      pathResult = pathJarFolder;
      if ((sFileName != null) && !sFileName.isEmpty())
        pathResult = pathResult.resolve(sFileName);
    return pathResult;