Car*_*tes 9 java spring spring-boot
我有一个spring boot web应用程序,我使用java -jar application.jar运行.我需要从代码中获取jar父文件夹路径.我怎么能做到这一点?
我已经尝试过这个,但没有成功.
Car*_*tes 18
那么,对我有用的是对这个答案的改编.代码是:
如果你使用java -jar myapp.jar运行dirtyPath将是这样的东西:jar:file:/ D:/arquivos/repositorio/myapp/trunk/target/myapp-1.0.3-RELEASE.jar!/ BOOT-INF /班!/ BR/COM/cancastilho /服务.或者如果你从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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
实际上,如果你使用spring boot,你可以像这样使用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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5646 次 |
| 最近记录: |