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

2022-09-04 06:48:58

我有一个弹簧引导Web应用程序,我使用java-jar应用程序运行.jar。我需要从代码中动态获取jar父文件夹路径。我怎样才能做到这一点?

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


答案 1

好吧,对我有用的是这个答案的改编。代码是:

如果你使用java -jar myapp运行.jar dirtyPath将接近这个:jar:file:/D:/arquivos/repositorio/myapp/trunk/target/myapp-1.0.3-RELEASE.jar!/BOOT-INF/classes!/br/com/cancastilho/service。或者,如果你从Spring Tools Suit运行,类似这样的东西:file:/D:/arquivos/repositorio/myapp/trunk/target/classes/br/com/cancastilho/service

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.

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

这对我有用,让我找到了我的罐子运行的路径,我希望这是你所期望的。


推荐