小编典典
嗯,对我有用的是对该答案的改编。代码是:
如果使用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;
}
编辑:
实际上,如果您使用的是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.
2020-05-30