如何在Spring Boot(Maven)项目中访问与src同级的文件?
Spring Boot读取项目根目录下JSON文件的路径方案
你的项目结构是app目录下包含pom.xml、src目录以及目标JSON文件(假设文件名为data.json),以下是两种可行的读取方案:
1. 使用Spring的Resource对象(推荐)
Spring的资源加载机制支持直接读取项目根目录的文件,有两种常用方式:
- 直接使用
FileSystemResource指定文件名:
import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; Resource jsonResource = new FileSystemResource("data.json"); // 后续可通过jsonResource.getInputStream()读取文件内容
- 注入
ResourceLoader(更符合Spring最佳实践):
import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; @Component public class JsonReader { private final ResourceLoader resourceLoader; public JsonReader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public Resource getJsonResource() { // 用file:前缀明确指定从文件系统加载,路径为项目根目录下的文件 return resourceLoader.getResource("file:data.json"); } }
2. 使用Java原生File对象
直接通过相对路径创建File实例即可,因为Java默认的相对路径基准是当前工作目录,而IDE运行Spring Boot或Maven命令时,工作目录默认就是pom.xml所在的项目根目录:
import java.io.File; File jsonFile = new File("data.json"); // 若担心工作目录不确定,可通过系统属性获取根目录再拼接: File jsonFile = new File(System.getProperty("user.dir") + "/data.json");
注意事项
- 若项目打包成Jar运行,Jar包外部的文件无法通过
ClassPathResource读取,必须使用上述FileSystemResource或File的方式。 - 确保目标JSON文件有读取权限,生产环境需注意文件路径的配置一致性。
内容的提问来源于stack exchange,提问作者stumped
相关产品推荐
相关产品推荐

