开发环境正常,生产环境springBoot获取不到资源文件

File file = ResourceUtils.getFile("classpath:templates/defaultBodyTemplate.docx");
源码分析
public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
        Assert.notNull(resourceUrl, "Resource URL must not be null");
        if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {  //URL_PROTOCOL_FILE="file"
            throw new FileNotFoundException(
                    description + " cannot be resolved to absolute file path " +
                    "because it does not reside in the file system: " + resourceUrl);
        }
        try {
            return new File(toURI(resourceUrl).getSchemeSpecificPart());
        }
        catch (URISyntaxException ex) {
            // Fallback for URLs that are not valid URIs (should hardly ever happen).
            return new File(resourceUrl.getFile());
        }
    }

       

        本地读取文件时, ResourceUtil.getFile(),读取本地的绝对路径,所以本地调试的时候没有问题,但是生成环境下JVM运行中 就找不到对应jar包中的文件ResourceUtil.getFile()就找不到文件;

        ResouceUtils.getFile()是专门用来加载非压缩和Jar包文件类型的资源,所以它根本不会去尝试加载Jar中的文件

方法一

       JVM中绝对路径的,路径是读取文件的当前类对应的classload来加载的,所以需要先获取到当前类的classload,然后通过classload的路径找文件相对于classload的相对路径,这时候,我们就需要使用上面的方法来读取。

InputStream stream =getClass()
        .getClassLoader()
        .getResourceAsStream(""templates/defaultBodyTemplate.docx"");
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));

方法二:

       只要用可以读取jar中文件的方式加载即可,比如 xx.class.getClassLoader().getResouceAsStream()这种以流的形式读取文件的方式.

File file =  new ClassPathResource("templates/defaultBodyTemplate.docx").getFile();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值