SpringBoot获取resources文件路径

解决方案

1、获取resources文件夹路径

File directory = new File("xxx/xxx/src/main/resources");
String reportPath = directory.getCanonicalPath();

xxx为你的项目内包的名称,File只会找到项目最外层地址;
这里需要注意,不能在xxx前面加/,否则只会找到顶层地址

我们的项目是从controller下获取resources下的文件:
在这里插入图片描述

	File directory = new File("src/main/resources");
    String reportPath = directory.getCanonicalPath();
    String resource =reportPath + "/static/template/resultTemplate.docx";
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在使用SpringBoot框架进行开发时,获取resources文件路径非常简单,只需要使用ClassLoader类加载器加载资源即可。具体实现方法如下: 1. 使用Java类中的getClassLoader()方法获取当前类的ClassLoader对象: ``` ClassLoader classLoader = getClass().getClassLoader(); ``` 2. 使用ClassLoader对象的getResource()或getResourceAsStream()方法获取resources文件夹中的资源: ``` URL url = classLoader.getResource("filename"); InputStream inputStream = classLoader.getResourceAsStream("filename"); ``` 其中,filename为需要获取的资源文件名。如果filename在resources文件夹的根目录下,则直接输入文件名即可;如果filename在resources文件夹的子目录下,则需要输入带有子目录的相对路径名。 例如,我们需要获取resources文件夹根目录下的config.properties文件,可以使用以下代码: ``` ClassLoader classLoader = getClass().getClassLoader(); URL url = classLoader.getResource("config.properties"); InputStream inputStream = classLoader.getResourceAsStream("config.properties"); ``` 获取resources文件夹下的子目录中的config.properties文件时,例如目录为/config,代码如下: ``` ClassLoader classLoader = getClass().getClassLoader(); URL url = classLoader.getResource("config/config.properties"); InputStream inputStream = classLoader.getResourceAsStream("config/config.properties"); ``` 通过以上方法可以轻松获取resources文件路径,从而读取其中的资源文件

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值