You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 16:12:32