将Java工程Build成可执行的Jar文件时,如Fat-Jar,有时候需要得到Jar的路径,从而可以读写所需的配置文件,在Eclipse中,一下代码可以正常运行:
MyCalss.class.getClassLoader().getResource("").getPath();
这样可以得到class文件的相对路径,但是如果Build成Jar包,就会出错,貌似是因为如果是Jar包,getClassLorder()会在classpath中查找文件,这样就会返回null,导致出错。Google了一下,通过以下方法可以得到jar包的相对路径:
String classpath = System.getProperty("java.class.path");
int jarPos = classpath.indexOf("MyJar.jar");
int jarPathPos = classpath.lastIndexOf(File.pathSeparatorChar, jarPos) + 1;
String path = classpath.substring(jarPathPos, jarPos);
原文地址:http://stackoverflow.com/questions/775389/accessing-properties-files-outside-the-jar?lq=1