SpringBoot获取项目文件的绝对路径和相对路径

1.场景

比如上传图片或者读取项目里的excel文件内容等,都需要准确获取文件路径

2.说明

项目代码大致样式

在这里插入图片描述

获取路径说明

所谓获取的相对路径,其实是获取项目打包后的target目录的路径,而不是咱们平常看到的代码路径,具体可查看下方图片

在这里插入图片描述

3.举例说明网上常见几种方法的路径获取结果

  1. request.getServletContext().getRealPath(“”)
  2. request.getServletContext().getRealPath(“/”)
  3. OperateExcelController.class.getResource(“”).getPath()
  4. OperateExcelController.class.getResource(“/”).getPath()
  5. OperateExcelController.class.getClassLoader().getResource(“static/尼克.jpg”).getPath()
  6. ResourceUtils.getURL(“classpath:”).getPath()

其中OperateExcelController为所在的类,ResourceUtils引入的是package org.springframework.util;

详情说明:
方法1、2的request.getServletContext().getRealPath(“”)和 request.getServletContext().getRealPath(“/”)
获得的路径不是项目路径,而是c盘下一个tomcat目录路径)
结果比如:C:\Users\211145187\AppData\Local\Temp\tomcat-docbase.8888.12632778012386910853\

方法3、4、5、6的OperateExcelController.class.getResource(“”).getPath()和OperateExcelController.class.getResource(“/”).getPath()和OperateExcelController.class.getClassLoader().getResource(“”).getPath()和ResourceUtils.getURL(“classpath:”).getPath()
实际获取的都是编译包里的根据经 比如:xx.class.getResource(“”).getPath()=xx.class.getResource(“/”).getPath()=xx.class.getClassLoader().getResource(“”).getPath()=ResourceUtils.getURL(“classpath:”).getPath()
结果比如:/E:/WorkSpace/demo/target/classes/

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")`。 希望这可以帮助到您!如果还有其他问题,请随时提问。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘大猫.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值