Something that is frustrating is that when you are developing in Eclipse MyClass.class.getProtectionDomain().getCodeSource().getLocation()
returns the /bin
directory which is great, but when you compile it to a jar, the path includes the /myjarname.jar
part which gives you illegal file names.
To have the code work both in the ide and once it is compiled to a jar, I use the following piece of code:
URL applicationRootPathURL = getClass().getProtectionDomain().getCodeSource().getLocation();
File applicationRootPath = new File(applicationRootPathURL.getPath());
File myFile;
if(applicationRootPath.isDirectory()){
myFile = new File(applicationRootPath, "filename");
}
else{
myFile = new File(applicationRootPath.getParentFile(), "filename");
}