如何获取正在运行的JAR文件的路径?

如何获取正在运行的JAR文件的路径?

我的代码在一个JAR文件中运行,比如说foo.jar,我需要在代码中知道运行foo.jar的文件夹。

所以,如果foo.jar在C:\FOO\,我想要获得该路径,无论我当前的工作目录是什么。


幕布斯6054654
浏览 3917回答 4
4回答

DIEA

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()     .toURI()).getPath();将“MyClass”替换为您班级的名称。显然,如果您的类是从非文件位置加载的,那么这会很奇怪。

烙印99

最适合我的解决方案:String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();String decodedPath = URLDecoder.decode(path, "UTF-8");这应该解决空格和特殊字符的问题。

Helenr

您还可以使用:CodeSource codeSource = YourMainClass.class.getProtectionDomain().getCodeSource();File jarFile = new File(codeSource.getLocation().toURI().getPath());String jarDir = jarFile.getParentFile().getPath();
打开App,查看更多内容
随时随地看视频慕课网APP