Market Tree

Welcome to the blog for Market Tree, the new web site for buying and selling goods and services in the UK

Category: Idle thoughts: software

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

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;

46 000 lines of code

Our buying and selling service is handled by just over 46 000 lines of computer code. This number will get larger as we add more features to our service.

“So what?” you might ask, or “Who cares?”, or even “What is code anyway?”. If you want to know what computer “code” is, then read on….

Computer code is just another name for computer commands or instructions in a computer program or application that tell a computer to do something. Below is an example of a simple computer method (a certain lump of code), written in the Java programming language, which adds up all the whole numbers from 1 to whatever number is specified.

Before you dive in, I just want to give you a very quick introduction to Java code.

  • The “//” characters are comment markers. Anything from these characters to the (right-hand) end of the line are ignored by the computer. These comments are for software developers to remind them what is going on – and here as a guide for you too.
  • The “{” and “}” brace characters group related lines of code together.
  • Most commands end with a “;” character.
  • A command like “int nSum = 0;” does two things; it declares a variable called “nSum” which stores an integer number, and then it sets this variable to store the value 0.

Okay, here’s the code:

// If n is more than zero then sum all the integers between one and n inclusive
// and return this sum.
// If n is less than or equal to zero then return zero.

public int sumWholeNumbersUpTo(int n)
  int nSum = 0;         // Declare and initialise our sum to zero

  int i = 1;            // Start counting from one
  while (i <= n)        // Do the next four lines if we have not finished yet
    nSum = nSum + i;    // We add the value of the counter to the sum
    i = i + 1;          // We increase the counter by one
  }                     // We go back to the "while" line

  return nSum;          // Tell the outside world the result

If we use this code by executing the following line (of code):

  int m = sumWholeNumbersUpTo(3);

we will find that the variable m is set to 6, which is 1 + 2 + 3.

Well, how was that for you?

How many lines of code are there for the “sumWholeNumbersUpTo(…)” method? Ignoring the 3 blank lines (put in to improve readability) and the 3 lines that are just comments without any computer instructions, we have 11 lines of code. More code will be needed (at least 1 line, as we have done above to get the result of 6) to use the method to actually work values out or do other useful stuff like talk to our database or interact with service users.

The number of 46 000 lines of Market Tree code excludes over 8 000 blank lines and more than 14 000 lines of nothing but comments.

Well, we hope that you have learned something interesting today!