SpringBoot获取项目绝对路径

SpringBoot获取项目绝对路径

String property = System.getProperty("user.dir");
String path = property + "/src/main/resources/static/files";
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 Spring Boot 项目中,您可以使用 `ResourceLoader` 接口来获取相对路径。`ResourceLoader` 是 Spring 框架中用于加载资源的接口,可以通过它来获取类路径下的文件、URL 资源等。 以下是一个示例,展示如何在 Spring Boot 项目获取相对路径: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; @Component public class ResourceExample { private final ResourceLoader resourceLoader; @Autowired public ResourceExample(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public String getRelativePath(String fileName) { try { // 使用 ResourceLoader 获取相对路径的资源 Resource resource = resourceLoader.getResource("classpath:" + fileName); return resource.getFile().getAbsolutePath(); } catch (Exception e) { // 异常处理 } return null; } } ``` 在上面的示例中,我们通过 `@Component` 注解将 `ResourceExample` 类声明为一个 Spring 组件,并通过构造函数注入了 `ResourceLoader` 对象。 然后,我们可以使用 `resourceLoader.getResource("classpath:" + fileName)` 方法获取指定文件名的资源。这里使用了 `"classpath:"` 前缀来指定资源是在类路径下查找。 最后,通过 `resource.getFile().getAbsolutePath()` 方法获取资源的绝对路径。 请注意,如果要获取的资源在类路径下的某个包中,可以在文件名中指定包路径。例如,如果要获取 `com/example/myfile.txt` 文件的相对路径,可以使用 `getRelativePath("com/example/myfile.txt")`。 希望这可以帮助到您!如果还有其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值