我有一个使用java-jar运行的Spring引导Web应用程序application.jar.我需要从代码中动态获取jar父文件夹路径。我怎么才能做到这一点?
我已经试过了,但没有成功。
嗯,对我起作用的是对这个答案的改编。代码为:
如果您使用java-jar myapp运行。jar目录路径将与以下内容非常接近:jar:file:/D:/arquivos/repositorio/myapp/trunk/target/myapp-1.0.3-RELEASE。罐子/引导INF/类/br/com/cancastilho/service。或者,如果您是从Spring Tools套装运行的,可以这样运行: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.
File file = new File(".");
logger.debug(file.getAbsolutePath());
这对我有用,让我的罐子运行的路径,我希望这是你所期待的。
试试这个代码
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));