对于Manifest中包含Main Class的可执行Jar:
当我使用java -jar myjar.jar启动它时,如何在运行时找到此jar的安装目录?
我想要做的是为Flyway开发一个命令行客户端。
该工具将使用以下文件夹结构进行安装:
INSTALLATION_PATH
|
-- bin
| |
| --start.sh (launches flyway.jar)
|
-- lib
| |
| --flyway.jar (contains Main class, loads flyway.properties)
|
-- conf
|
--flyway.properties (configuration)
flyway.jar如何解析INSTALLATION_PATH?
答案 0 :(得分:6)
您可以尝试:
// this generally returns the PWD
String pwd = System.getProperties().getProperty("user.dir");
// or you can get the location of the URL
// from the .jar file in which your class was loaded
// you may want to then simply back it up a level with ".."
URL yourJar = getClass().getProtectionDomain().getCodeSource().getLocation();
答案 1 :(得分:1)
以下内容将为您提供起始目录:
new File(".").getAbsolutePath()
答案 2 :(得分:0)
执行此操作而不是尝试在运行时找到安装目录的首选方法是:
执行安装,然后编辑系统类路径属性以添加此jar和任何相关的jar
之后,您可以从任何目录运行它
当然,这样做的好处是,您只需在安装时设置一次类路径。每次决定运行时都不需要在运行时找到安装目录。