繁体   English   中英

获取 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()获取 stream 。 如果要记录文件的位置,请使用Resource.getURL()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM