我有一个Spring boot Web应用程序,我使用 java -jar application.jar 运行。我需要从代码中动态获取jar父文件夹路径。我怎么能做到这一点?
我已经尝试了this,但没有成功。
答案 0 :(得分:14)
嗯,对我有用的是对this answer的改编。 代码是:
如果你使用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运行,可能是这样的: 文件:/ 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.
答案 1 :(得分:0)
File file = new File(".");
logger.debug(file.getAbsolutePath());
这对我来说是运行我的jar运行的路径,我希望这是你所期待的。
答案 2 :(得分:0)
尝试此代码
public static String getParentRealPath(URI uri) throws URISyntaxException {
if (!"jar".equals(uri.getScheme()))
return new File(uri).getParent();
do {
uri = new URI(uri.getSchemeSpecificPart());
} while ("jar".equals(uri.getScheme()));
File file = new File(uri);
do {
while (!file.getName().endsWith(".jar!"))
file = file.getParentFile();
String path = file.toURI().toString();
uri = new URI(path.substring(0, path.length() - 1));
file = new File(uri);
} while (!file.exists());
return file.getParent();
}
URI uri = clazz.getProtectionDomain().getCodeSource().getLocation().toURI();
System.out.println(getParentRealPath(uri));