Java Desktop Application Root Directory

1

I have a java desktop application, being an executable jar and I need to know the root directory where the jar is running. I have researched several ways and I have not found what I need, I am always seeing models where I inform an X file so it returns me the location of the same and what I need and get the Root of the Executable Jar.

Thank you.

    
asked by anonymous 23.03.2016 / 14:04

2 answers

1

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

    
24.03.2016 / 21:53
1

Solution for 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 post: link

    
23.03.2016 / 14:28