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 2024-05-10 14:06  C_C_菜园  阅读(5)  评论(0编辑  收藏  举报

导航