【问题标题】:Get absolute path of resource file inside a jar获取jar内资源文件的绝对路径
【发布时间】:2020-11-26 10:48:51
【问题描述】:

我想访问当前运行的 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

【问题讨论】:

标签: java spring-boot file jar


【解决方案1】:

您不能使用File 访问template.shFile 用于引用文件系统中的文件。在您的情况下,您正在尝试引用 jar 文件中的某些内容。

如果您想阅读template.sh 的内容,请使用Resource.getInputStream() 获取流。如果要记录文件的位置,请使用Resource.getURL()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2013-04-11
    • 2010-10-30
    • 2021-12-21
    • 2011-04-25
    相关资源
    最近更新 更多