Skip to content

Instantly share code, notes, and snippets.

@dantheman213
Last active November 2, 2015 22:54
Show Gist options
  • Save dantheman213/47e2c68bb86866ebe310 to your computer and use it in GitHub Desktop.
Save dantheman213/47e2c68bb86866ebe310 to your computer and use it in GitHub Desktop.
Java Get Full Application Path Cross Platform
public class AppPath {
public String getAppPath() {
URL url;
String extURL;
Class anyClass = this.getClass();
try {
url = anyClass.getProtectionDomain().getCodeSource().getLocation();
} catch (SecurityException ex) {
url = anyClass.getResource(anyClass.getSimpleName() + ".class");
}
extURL = url.toExternalForm();
// prune for various cases
if (extURL.endsWith(".jar"))
extURL = extURL.substring(0, extURL.lastIndexOf("/"));
else {
// from getResource
String suffix = "/"+(anyClass.getName()).replace(".", "/")+".class";
extURL = extURL.replace(suffix, "");
if (extURL.startsWith("jar:") && extURL.endsWith(".jar!"))
extURL = extURL.substring(4, extURL.lastIndexOf("/"));
}
// convert back to url
try {
url = new URL(extURL);
} catch (MalformedURLException mux) {
}
// convert url to File
File fPath = null;
try {
fPath = new File(url.toURI());
} catch(URISyntaxException ex) {
fPath = new File(url.getPath());
}
// finally, convert File to String
if(fPath != null) {
File fDir = fPath.getAbsoluteFile();
return fDir.toString() + File.separator;
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment