Skip to content

Instantly share code, notes, and snippets.

@vaibhaw
Created December 9, 2014 10:16
Show Gist options
  • Save vaibhaw/bb0af8a76018a22b9c9d to your computer and use it in GitHub Desktop.
Save vaibhaw/bb0af8a76018a22b9c9d to your computer and use it in GitHub Desktop.
Java Code snippets for everyday tasks
// ======> get path of running jar file
// Solutions act funny for non-file locations
// Solution:1
String path = MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath(); // gives path, acts funny if path has spaces
String decodedPath = URLDecoder.decode(path, "UTF-8"); // to solve problem related to whitespaces in path
// Solution:2
// URLDecoder does not work for many special characters
// toURI is vital here as it takes care of URL encoding/decoding
String path = MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();‌
// Solution:3
// If jar is not executed from terminal e.g. double-clicked, following solution would work
String path = ClassLoader.getSystemClassLoader().getResource(".").getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
String folderPath = (new File(path)).getParentFile().getPath(); // Or
String folderParh = path.substring(0, path.lastIndexOf("") + 1);
/* Summary
To obtain the File for a given Class, there are two steps:
Convert the Class to a URL & Convert the URL to a File
*/
/* Convert URL to File */
/* There are two major ways to find a URL relevant to a Class */
URL url = Bar.class.getProtectionDomain().getCodeSource().getLocation();
URL url = Bar.class.getResource(Bar.class.getSimpleName() + ".class");
/* Convert URL to File */
File f = new File(url.toURI())
String folderPath = f..getParentFile().getPath();
// Ref# http://stackoverflow.com/a/12733172/925216
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment