【问题标题】:Executable Jar installation path可执行Jar安装路径
【发布时间】:2011-01-10 22:08:11
【问题描述】:

对于 Manifest 中带有 Main 类的可执行 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?

【问题讨论】:

    标签: java installation classpath executable-jar


    【解决方案1】:

    你可以试试:

    // 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();
    

    【讨论】:

      【解决方案2】:

      以下将为您提供起始目录:

      new File(".").getAbsolutePath()
      

      【讨论】:

      • 是的,但是这假设 INSTALLATION_PATH = 当前目录,这可能并不总是正确的。
      【解决方案3】:

      执行此操作而不是尝试在运行时查找安装目录的首选方法是:
      进行安装,然后编辑系统类路径属性以添加此 jar 和任何依赖的 jar。
      之后,您可以从任何目录运行它。
      好处当然是这样,您在安装时只设置一次类路径。每次决定运行时无需在运行时查找安装目录。

      【讨论】:

      • 我的问题不是找不到jar,而是jar必须找到属性。
      猜你喜欢
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 2017-02-04
      • 1970-01-01
      • 2014-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多