获取jar中资源文件的绝对路径
Get absolute path of resource file inside a jar
我想访问当前 jar 的资源文件夹中的文件 运行。
该文件位于 My_app.jar
内,位于 /apps/dashboard/
我试过这样访问它
String customScriptPath = "script/template.sh";
public String getTemplatePath() {
Resource temp= new ClassPathResource(this.customScriptPath, this.getClass().getClassLoader());
try {
File templateFile = temp.getFile();
logger.info("Script template path = "+templateFile.getAbsolutePath());
return templateFile.getAbsolutePath();
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
return null;
}
我遇到了这个错误
class path resource [script/template.sh] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/apps/dashboard/My_app.jar!/BOOT-INF/classes!/script/template.sh
您不能使用 File
访问 template.sh
。 File
用于引用文件系统中的文件。在您的情况下,您正在尝试引用 jar 文件中的内容。
如果您想阅读 template.sh
的内容,请使用 Resource.getInputStream()
获取流。如果要记录文件的位置,请使用 Resource.getURL()
.
我想访问当前 jar 的资源文件夹中的文件 运行。
该文件位于 My_app.jar
内,位于 /apps/dashboard/
我试过这样访问它
String customScriptPath = "script/template.sh";
public String getTemplatePath() {
Resource temp= new ClassPathResource(this.customScriptPath, this.getClass().getClassLoader());
try {
File templateFile = temp.getFile();
logger.info("Script template path = "+templateFile.getAbsolutePath());
return templateFile.getAbsolutePath();
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
return null;
}
我遇到了这个错误
class path resource [script/template.sh] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/apps/dashboard/My_app.jar!/BOOT-INF/classes!/script/template.sh
您不能使用 File
访问 template.sh
。 File
用于引用文件系统中的文件。在您的情况下,您正在尝试引用 jar 文件中的内容。
如果您想阅读 template.sh
的内容,请使用 Resource.getInputStream()
获取流。如果要记录文件的位置,请使用 Resource.getURL()
.