Java Desktop Application Root Directory

Asked

Viewed 1,151 times

1

I have a java desktop application, being an executable jar and need to know the root directory where the jar is running. I’ve searched several ways and I haven’t found what I need, I’m always seeing models where I inform an X file to return me the location of the same and what I need and get the Executable Jar Root.

Thanks.

  • 1

    Try one of these: http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file

  • Thank you for the indication. I found the reply there.

2 answers

1

Solution to what I need:

The only Solution that Works for me on Linux, Mac and Windows:

public static String getJarContainingFolder(Class aclass) throws Exception {
  CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();

  File jarFile;

  if (codeSource.getLocation() != null) {
    jarFile = new File(codeSource.getLocation().toURI());
  }
  else {
    String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();
    String jarFilePath = path.substring(path.indexOf(":") + 1, path.indexOf("!"));
    jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
    jarFile = new File(jarFilePath);
  }
  return jarFile.getParentFile().getAbsolutePath();
}

found in the post: https://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file

1


You can use String path = new File(".").getCanonicalPath(); for this.

  • This does not answer the question. It only returns the user folder, not the one the jar is running.

  • Edited, actually the previous answer returns the folder where the user executed the jar.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.