In my application, the class that start the application is put at %INSTALLED_APP_HOME%/lib. In my code, I need get the path of %INSTALLED_APP_HOME%.
The code looks like below[CodeWorks]
The only trick here is this line: File jarPath = new File(url.toURI());
If we change to File jarPath = new File(url.getPath()); It will not work. This is the path in the url is encoded(not completely), for example space is converted to %20.
if the url is: "C:/jeffery/project/jeffery + project/lib, url.getPath()" would be "C:/jeffery/project/jeffery%20+%20project/lib".
File jarPath = new File(url.getPath()) obviously would points to wrong (not exist ) location.
Then I tried
baseLocation = URLDecoder.decode(baseLocation, System.getProperty("file.encoding"));
In most case it woors, but it DOES NOT work when the path contains +. Because URLDecoder.decode will convert + in the original path to a space " " improperly.
The base location would be" C:/jeffery/project/jeffery project/lib - two space between jeffery and project because + is convert to space " " improperly.
The correct code should be like in section [CodeWorks].
Alternatively, we can use:
ResourceThe code looks like below[CodeWorks]
private String getBaseLocation() throws IOException { try { URL url = this.getClass().getProtectionDomain().getCodeSource() .getLocation(); File jarPath = new File(url.toURI()); // NOT File jarPath = new File(url.getPath()); String baseLocation = jarPath.getParentFile().getParent(); return baseLocation; } } catch (Exception e) { throw new IOException(e); } }
If we change to File jarPath = new File(url.getPath()); It will not work. This is the path in the url is encoded(not completely), for example space is converted to %20.
if the url is: "C:/jeffery/project/jeffery + project/lib, url.getPath()" would be "C:/jeffery/project/jeffery%20+%20project/lib".
File jarPath = new File(url.getPath()) obviously would points to wrong (not exist ) location.
Then I tried
baseLocation = URLDecoder.decode(baseLocation, System.getProperty("file.encoding"));
In most case it woors, but it DOES NOT work when the path contains +. Because URLDecoder.decode will convert + in the original path to a space " " improperly.
The base location would be" C:/jeffery/project/jeffery project/lib - two space between jeffery and project because + is convert to space " " improperly.
The correct code should be like in section [CodeWorks].
Alternatively, we can use:
String baseLocation = jarPath.getParentFile().getParent();
baseLocation = baseLocation.replace("+", "%2B"); // add this line
baseLocation = URLDecoder.decode(baseLocation, System.getProperty("file.encoding")
http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file