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);
}
}
}
标签:Resource,SpringBoot,resourceLoader,springframework,io,org,import,Resources,读取
From: https://www.cnblogs.com/kakarotto-chen/p/18184192