看完!我不允许你还不知道 Spring Boot如何读取Resource目录文件
🌷 古之立大事者,不惟有超世之才,亦必有坚忍不拔之志
🎐 个人CSND主页——Micro麦可乐的博客
🐥《Docker实操教程》专栏以最新的Centos版本为基础进行Docker实操教程,入门到实战
🌺《RabbitMQ》专栏19年编写主要介绍使用JAVA开发RabbitMQ的系列教程,从基础知识到项目实战
🌸《设计模式》专栏以实际的生活场景为案例进行讲解,让大家对设计模式有一个更清晰的理解
🌛《开源项目》本专栏主要介绍目前热门的开源项目,带大家快速了解并轻松上手使用
🍎 《前端技术》专栏以实战为主介绍日常开发中前端应用的一些功能以及技巧,均附有完整的代码示例
✨《开发技巧》本专栏包含了各种系统的设计原理以及注意事项,并分享一些日常开发的功能小技巧
💕《Jenkins实战》专栏主要介绍Jenkins+Docker的实战教程,让你快速掌握项目CI/CD,是2024年最新的实战教程
🌞《Spring Boot》专栏主要介绍我们日常工作项目中经常应用到的功能以及技巧,代码样例完整
👍《Spring Security》专栏中我们将逐步深入Spring Security的各个技术细节,带你从入门到精通,全面掌握这一安全技术
如果文章能够给大家带来一定的帮助!欢迎关注、评论互动~
看完!我不允许你还不知道Spring Boot如何读取Resource目录文件
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,可直接从类路径获取资源
importorg.springframework.core.io.ClassPathResource;importorg.springframework.util.FileCopyUtils;importjava.io.InputStreamReader;importjava.nio.charset.StandardCharsets;publicclassResourceReader{publicStringreadWithClassPathResource(String filePath)throwsException{ClassPathResource resource =newClassPathResource(filePath);try(InputStreamReader reader =newInputStreamReader( resource.getInputStream(),StandardCharsets.UTF_8)){returnFileCopyUtils.copyToString(reader);}}}测试示例:
String content =readWithClassPathResource("data/sample.txt");System.out.println(content);2.2 使用 ResourceLoader
ResourceLoader 是 Spring 上下文提供的通用资源加载接口,支持多种前缀(classpath:、file:、http: 等)
importorg.springframework.core.io.Resource;importorg.springframework.core.io.ResourceLoader;importorg.springframework.stereotype.Component;importjava.io.IOException;importjava.nio.charset.StandardCharsets;@ComponentpublicclassResourceService{privatefinalResourceLoader resourceLoader;publicResourceService(ResourceLoader resourceLoader){this.resourceLoader = resourceLoader;}publicStringreadWithResourceLoader(String location)throwsException{Resource resource = resourceLoader.getResource(location);try(InputStream in = resource.getInputStream()){byte[] bytes = in.readAllBytes();returnnewString(bytes,StandardCharsets.UTF_8);}}}测试示例:
// 读取 classpath 下的 sample.txtString text = resourceLoaderService.readWithResourceLoader("classpath:data/sample.txt");2.3 使用 @Value 注解
如果只是读取小片段文本或 URL,可直接在字段或方法参数上使用 @Value
importorg.springframework.beans.factory.annotation.Value;importorg.springframework.core.io.Resource;importorg.springframework.stereotype.Component;importjava.io.IOException;importjava.nio.charset.StandardCharsets;@ComponentpublicclassValueResourceReader{@Value("classpath:data/sample.txt")privateResource configFile;publicStringreadConfig()throwsIOException{returnnewString(configFile.getInputStream().readAllBytes(),StandardCharsets.UTF_8);}}2.4 使用 ResourceUtils
ResourceUtils 是 Spring 内置的一个工具类, 可以将类路径资源转换为 File 或 URL,适用于需要 java.io.File 操作的场景
importorg.springframework.stereotype.Service;importorg.springframework.util.ResourceUtils;importjava.io.File;importjava.nio.file.Files;importjava.nio.charset.StandardCharsets;@ServicepublicclassResourceUtilsService{publicStringreadWithResourceUtils(String location)throwsException{// location 形如:"classpath:data/sample.txt"File file =ResourceUtils.getFile(location);byte[] bytes =Files.readAllBytes(file.toPath());returnnewString(bytes,StandardCharsets.UTF_8);}}2.5 通过 getResourceAsStream
最原生的方式:通过 Class 或 ClassLoader 的 getResourceAsStream
importorg.springframework.stereotype.Service;importjava.io.BufferedReader;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.nio.charset.StandardCharsets;importjava.util.stream.Collectors;@ServicepublicclassNativeStreamService{publicStringreadWithGetResourceAsStream(String path){try(InputStream in =this.getClass().getClassLoader().getResourceAsStream(path);BufferedReader reader =newBufferedReader(newInputStreamReader(in,StandardCharsets.UTF_8))){return reader.lines().collect(Collectors.joining(System.lineSeparator()));}catch(Exception e){thrownewRuntimeException("读取资源失败", e);}}}补充:读取Properties文件
有小伙伴说,读取的配置文件是Properties文件,要如何来读取?下面博主做一个补充,依然使用 ClassPathResource 读取文件
importorg.springframework.core.io.ClassPathResource;importjava.io.IOException;importjava.io.InputStream;importjava.util.Properties;publicclassPropertiesReader{publicPropertiesreadProperties(String filePath)throwsIOException{ClassPathResource resource =newClassPathResource(filePath);try(InputStream input = resource.getInputStream()){Properties properties =newProperties(); properties.load(input);return properties;}}}3. 完整实战案例:读取CSV文件并处理
下面我们通过一个实战案例,来加深小伙伴的理解
3.1 创建测试文件
在 src/main/resources/data/ 下创建users.csv:
id,name,email 1,张三,[email protected],李四,[email protected]3.2 创建CSV处理器
importorg.springframework.core.io.ClassPathResource;importorg.springframework.stereotype.Service;importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.util.ArrayList;importjava.util.List;@ServicepublicclassCsvService{publicList<User>parseCsv(String filePath)throwsException{ClassPathResource resource =newClassPathResource(filePath);List<User> users =newArrayList<>();try(BufferedReader reader =newBufferedReader(newInputStreamReader(resource.getInputStream()))){// 跳过标题行String line = reader.readLine();while((line = reader.readLine())!=null){String[] parts = line.split(",");if(parts.length ==3){ users.add(newUser(Integer.parseInt(parts[0]), parts[1], parts[2]));}}}return users;}publicstaticclassUser{privateint id;privateString name;privateString email;// 构造方法、getters和toString}}3.3 创建Controller测试
importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RestController;importjava.util.List;@RestControllerpublicclassCsvController{privatefinalCsvService csvService;publicCsvController(CsvService csvService){this.csvService = csvService;}@GetMapping("/users")publicList<CsvService.User>getUsers()throwsException{return csvService.parseCsv("data/users.csv");}}启动应用后访问:http://localhost:8080/users
输出结果
看到输出如下数据证明已经读取成功
[{"id":1,"name":"张三","email":"[email protected]"},{"id":2,"name":"李四","email":"[email protected]"}]4. 常见问题解决方案
问题1:文件路径错误
错误信息:java.io.FileNotFoundException: class path resource [xxx] cannot be opened because it does not exist
解决方案:
检查文件是否在src/main/resources目录下
使用正确路径(区分大小写)
文件路径前不要加/(正确:data/file.txt,错误:/data/file.txt)
问题2:打包后文件读取失败
错误信息:FileNotFoundException when reading from JAR
解决方案:
使用ClassPathResource而不是File
避免使用new File(“classpath:…”)语法
使用getResourceAsStream()方法
问题3:读取Resource目录文件中文乱码
解决方案:
// 明确指定UTF-8编码newInputStreamReader(resource.getInputStream(),StandardCharsets.UTF_8);5. 总结
Spring Boot提供了多种灵活的方式来读取resource目录下的文件。根据不同场景选用最合适的方式:
- 如果需要
Spring统一管理,推荐ResourceLoader; - 若只是简单注入小文件,可选 @Value;
- 如果需要操作 File,可用 ResourceUtils。
掌握这些方法,能让小伙伴们在处理配置、模板、静态资源等场景时更得心应手,如果你在实践过程中有任何疑问或更好的扩展思路,欢迎在评论区留言,最后希望大家一键三连给博主一点点鼓励!
专栏最新回顾
【01】ThreadLocal的原理以及实际应用技巧详解 - 如何在身份认证场景Token中传递获取用户信息
【02】基于MyBatis-Plus Dynamic-Datasource实现 SaaS 系统动态租户数据源管理
【03】基于nacos实现动态线程池设计与实践:告别固定配置,拥抱弹性调度
【04】Java常用加密算法详解与实战代码 - 附可直接运行的测试示例
【05】Java synchronized 锁机制深度解析与实战指南 - 银行转账案例
【06】还在为线上BUG苦苦找寻?试试IntelliJ IDEA远程调试线上Java程序
【07】使用 Apache Commons Exec 自动化脚本执行实现 MySQL 数据库备份
【08】JAVA开发中几个常用的lambda表达式!记得收藏起来哦~