我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
当前回答
getProtectionDomain方法有时可能不起作用,例如当你必须为一些核心java类(例如在我的情况下,IBM JDK中的StringBuilder类)找到jar时,但是下面的工作是无缝的:
public static void main(String[] args) {
System.out.println(findSource(MyClass.class));
// OR
System.out.println(findSource(String.class));
}
public static String findSource(Class<?> clazz) {
String resourceToSearch = '/' + clazz.getName().replace(".", "/") + ".class";
java.net.URL location = clazz.getResource(resourceToSearch);
String sourcePath = location.getPath();
// Optional, Remove junk
return sourcePath.replace("file:", "").replace("!" + resourceToSearch, "");
}
其他回答
在我最终找到一个有效(且简短)的解决方案之前,我不得不浪费很多时间。 有可能jarLocation带有一个像file:\或jar:file\这样的前缀,可以使用String#substring()来删除。
URL jarLocationUrl = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
String jarLocation = new File(jarLocationUrl.toString()).getParent();
对我来说最好的解决方案:
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
这应该可以解决空格和特殊字符的问题。
我用Java 7编写,用Oracle的运行时在Windows 7上测试,用开源运行时在Ubuntu上测试。这对于这些系统来说是完美的:
任何正在运行的jar文件的父目录的路径(假设调用这段代码的类是jar存档本身的直接子目录):
try {
fooDir = new File(this.getClass().getClassLoader().getResource("").toURI());
} catch (URISyntaxException e) {
//may be sloppy, but don't really need anything here
}
fooDirPath = fooDir.toString(); // converts abstract (absolute) path to a String
因此,foo.jar的路径是:
fooPath = fooDirPath + File.separator + "foo.jar";
同样,这也没有在任何Mac或旧版本的Windows上进行测试
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
将“MyClass”替换为类名。
显然,如果您的类是从非文件位置加载的,这将会做一些奇怪的事情。
我很惊讶地发现,最近没有人建议使用Path。以下是引用:“Path类包括各种方法,可用于获取路径信息、访问路径元素、将路径转换为其他形式或提取路径的部分”
因此,一个好的替代方法是获取Path对象为:
Path path = Paths.get(Test.class.getProtectionDomain().getCodeSource().getLocation().toURI());