1. 前言
在 Spring Boot 开发中,我们经常需要读取 src/main/resources 目录下的文件。src/main/resources 目录下通常存放配置文件、模板、静态资源、SQL 脚本等,如何在运行时读取这些资源,是每个 Java 开发者必须掌握的技能。

比如下面的 Spring Boot 项目中,资源文件的存储位置:
src/
└── main/
└── resources/
├── static/ # 静态资源
├── templates/ # 模板文件
├── config/ # 配置文件
└── data/ # 数据文件
本文将详细介绍在 Spring Boot 中读取类路径(classpath)下资源的方法,并给出完整的代码示例。
2. 读取 Resource 文件的五种常见方式
2.1 使用 ClassPathResource(推荐)
Spring 提供了 ClassPathResource,可直接从类路径获取资源。
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class ResourceReader {
public String readWithClassPathResource(String filePath) throws Exception {
ClassPathResource resource = new ClassPathResource(filePath);
try ( (
resource.getInputStream(), StandardCharsets.UTF_8)) {
FileCopyUtils.copyToString(reader);
}
}
}


