Last active
November 2, 2015 22:54
-
-
Save dantheman213/47e2c68bb86866ebe310 to your computer and use it in GitHub Desktop.
Java Get Full Application Path Cross Platform
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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