如何获得弹簧启动应用程序jar父文件夹路径dinamically?

问题描述:

我有一个弹簧启动web应用程序,我运行使用java -jar application.jar。我需要从代码中获取jar父文件夹路径。我怎么能做到这一点?如何获得弹簧启动应用程序jar父文件夹路径dinamically?

我已经试过this,但没有成功。

+0

欢迎堆栈溢出,请阅读[如何提问](https://开头计算器.COM /帮助/ HO w-to-ask)和[如何创建最小,完整和可验证的示例](https://*.com/help/mcve)。在提问之前,始终要具体并尽力而为。在这种情况下,你提到你尝试了一个解决方案,但是你的错误是什么,或者你的基本实现是什么。 – Teocci

+0

如果我从** java -jar application.jar **的终端上显示该代码的代码将返回null。我将把代码放在这里: 'MyCustomClass.class.getProtectionDomain()。getCodeSource()。getLocation()。toURI()。getPath();' 如果我使用Spring Tools Suit IDE播放按钮,这段代码的结果是: '/ D:/ arquivos/repositorio/myapp/trunk/target/classes /' –

那么,我的工作是this answer改编。 的代码是:

如果您运行使用Java的罐子myapp.jar dirtyPath将一些接近 本中:jar:文件:/ d:/ arquivos/repositorio/MYAPP /主干/目标/ myapp- 1.0.3-RELEASE.jar!/ BOOT-INF/classes中!/ BR/COM/cancastilho /服务。 或者,如果你从Spring这样的工具套装,像这样运行: 文件:/ d:/ arquivos/repositorio/MYAPP /主干/目标/班/ BR/COM/cancastilho /服务

public String getParentDirectoryFromJar() { 
    String dirtyPath = getClass().getResource("").toString(); 
    String jarPath = dirtyPath.replaceAll("^.*file:/", ""); //removes file:/ and everything before it 
    jarPath = jarPath.replaceAll("jar!.*", "jar"); //removes everything after .jar, if .jar exists in dirtyPath 
    jarPath = jarPath.replaceAll("%20", " "); //necessary if path has spaces within 
    if (!jarPath.endsWith(".jar")) { // this is needed if you plan to run the app using Spring Tools Suit play button. 
     jarPath = jarPath.replaceAll("/classes/.*", "/classes/"); 
    } 
    String directoryPath = Paths.get(jarPath).getParent().toString(); //Paths - from java 8 
    return directoryPath; 
} 

编辑:

其实,如果你使用的弹簧启动,你可以只使用ApplicationHome类是这样的:

ApplicationHome home = new ApplicationHome(MyMainSpringBootApplication.class); 
home.getDir(); // returns the folder where the jar is. This is what I wanted. 
home.getSource(); // returns the jar absolute path. 

File file = new File("."); 
    logger.debug(file.getAbsolutePath()); 

这工作对我来说是我的jar运行的路径,我希望这是你的期望。

+0

这段代码将返回我发出java -jar命令的文件夹路径。 如果我从我的目标文件夹中运行它: CD d:\ arquivos \ repositorio \ MYAPP \干线\目标 Java的罐子application.jar 我会得到这样的结果: 'd:\ arquivos \ repositorio \ MYAPP \干线\目标\ .' 如果我从一个外部文件夹中运行它,让我们说: CD d:\ arquivos \ repositorio \ MYAPP \干线\ Java的罐子目标\ application.jar 我'会得到:'D:\ arquivos \ repositorio \ myapp \ trunk \ .' 它部分地解决了我的问题。即使我从另一个外部文件夹发出命令,是否有办法找到路径? –