SpringBoot读取Resources下的文件
1.SpringBoot的基础2.SpringBoot的@Resource和@Autowired+@Qualifier使用3.SpringBoot配置两个一样的Bean,区分两个配置类——@Primary4.SpringBoot项目预加载数据——ApplicationRunner、CommandLineRunner、InitializingBean 、@PostConstruct区别5.SpringBoot获取配置:@Value、@ConfigurationProperties方式6.SpringBoot注入时设置《多例》7.在线程中使用Spring的Bean的方法、不推荐把“线程”注入到Spring
8.SpringBoot读取Resources下的文件
package com.qzsl.dp.utils; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; import org.springframework.util.FileCopyUtils; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; /** 获取初始化文件 * @author -- * @since 2024/5/10 **/ @Component public class ResourceReader { private final ResourceLoader resourceLoader; public ResourceReader(@Qualifier("gridFsTemplate") ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } /** 读取resources下的文件 * @param fileName 如:/q.txt 或者(在sql文件夹下) /sql/text.sql * @return {@link String} * @since 2024/5/10 **/ public String readResourceFile(String fileName) throws IOException { // 获取资源文件的 Resource 对象 Resource resource = resourceLoader.getResource("classpath:" + fileName); // 检查资源文件是否存在 if (resource.exists()) { // 使用 try-with-resources 自动关闭 Reader try (Reader reader = new InputStreamReader(resource.getInputStream())) { // 使用 FileCopyUtils 将内容读取到字符串中 return FileCopyUtils.copyToString(reader); } } else { throw new IOException("Resource file not found: " + fileName); } } }
合集:
SpringBoot基础
分类:
SpringBoot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报