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

如何让SpringBoot找到src/main/resources目录下的文件

解决方案

核心问题原因

src/main/resources下的文件在项目编译打包后会被放入classpath根目录,而FileReader是基于系统本地文件路径读取,无法直接访问classpath内的资源(尤其是打包成Jar包后,资源并非独立的系统文件)。

修改步骤

  1. 调整配置文件路径
    在application.properties(或application.yml)中,将vocab.lookup.mapper的值改为资源文件的相对文件名(无需路径前缀)。例如:

    vocab.lookup.mapper=vocab-lookup.csv
    

    如果文件放在src/main/resources/csv子目录下,则配置为:

    vocab.lookup.mapper=csv/vocab-lookup.csv
    
  2. 修改LookupMapper的资源读取逻辑
    使用Spring提供的ClassPathResource来读取classpath内的资源,替换原有的FileReader实现:

    @Component
    public class LookupMapper {
    
        public HashMap<String, LookUp> entry = new HashMap<>();
    
        @Autowired
        public LookupMapper(@Value("${vocab.lookup.mapper}") String vocabLookupFileName) throws IOException {
            // 用ClassPathResource读取classpath资源,指定UTF-8编码避免乱码
            try (CSVReader csvReader = new CSVReader(
                    new InputStreamReader(
                            new ClassPathResource(vocabLookupFileName).getInputStream(),
                            StandardCharsets.UTF_8
                    )
            )) {
                String[] values = null;
                while ((values = csvReader.readNext()) != null) {
                    LookUp lookUp = new LookUp(values[1], Boolean.parseBoolean(values[2]));
                    this.entry.put(values[0].toUpperCase(), lookUp);
                }
            }
        }
    }
    

额外说明

  • ClassPathResource会自动适配开发环境和打包后的Jar环境,无论资源是在本地文件系统还是Jar包内,都能正确读取。
  • 若需要处理大文件或更复杂的资源加载,也可以注入ResourceLoader来实现,逻辑和ClassPathResource一致。

内容的提问来源于stack exchange,提问作者Timothy Clotworthy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:15:19