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);
}
}
}

posted on   C_C_菜园  阅读(182)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示