当前位置: 首页 > news >正文

springboot项目读取 resources 目录下的文件的9种方式

1. 使用 ClassLoader.getResourceAsStream() 方法

InputStream inputStream = getClass().getClassLoader().getResourceAsStream(“file.txt”);

2.使用 Class.getResourceAsStream() 方法

InputStream inputStream = getClass().getResourceAsStream(“/file.txt”);

3.使用 ResourceLoader 加载文件

@Autowired private ResourceLoader resourceLoader;

Resource resource = resourceLoader.getResource(“classpath:file.txt”); InputStream inputStream = resource.getInputStream();

4.使用 ResourceUtils 加载文件

File file = ResourceUtils.getFile(“classpath:file.txt”);

5. 使用 ApplicationContext 加载文件

@Autowired private ApplicationContext applicationContext;

Resource resource = applicationContext.getResource(“classpath:file.txt”); InputStream inputStream = resource.getInputStream();

6.使用 ServletContext 加载文件

@Autowired private ServletContext servletContext;

InputStream inputStream = servletContext.getResourceAsStream(“/WEB-INF/classes/file.txt”);

7. 使用 File System 加载文件

File file = new File(“src/main/resources/file.txt”); InputStream inputStream = new FileInputStream(file);

8. 使用 Paths 和 Files 加载文件

Path path = Paths.get(“src/main/resources/file.txt”); InputStream inputStream = Files.newInputStream(path);

9. 使用 ClassPathResource 加载文件 (springboot项目 读取resources 推荐使用)

ClassPathResource resource = new ClassPathResource(“file.txt”); InputStream inputStream = resource.getInputStream();

案例: 模拟springboot 装配bean

配置文件

package com.ldj.springboot.importbean.selector;

import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

/**
 * User: ldj
 * Date: 2024/8/24
 * Time: 23:54
 * Description: No Description
 */
public class MyBeanSelector implements ImportSelector {

    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        List<String> springBeanPaths = SpringFactoriesLoader.getSpringBeanPaths("spring.factories");
        if (CollectionUtils.isEmpty(springBeanPaths)) {
            throw new RuntimeException("spring.factories文件 缺少配置!");
        }
        return springBeanPaths.toArray(new String[0]);
    }
}

// 读取要注入容器的类所在路径的配置文件
class SpringFactoriesLoader {
    public static List<String> getSpringBeanPaths(String path) {
        List<String> classPaths = new LinkedList<>();
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        String str;
        try {
            ClassPathResource classPathResource = new ClassPathResource(path);
            inputStream = classPathResource.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            while ((str = bufferedReader.readLine()) != null) {
                System.out.println(str);
                classPaths.add(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return classPaths;
    }

}


package com.ldj.springboot.importbean;

import com.ldj.springboot.importbean.config.ProductConfig;
import com.ldj.springboot.importbean.config.StoreConfig;
import com.ldj.springboot.importbean.selector.MyBeanSelector;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Import;

@Import(value = {MyBeanSelector.class})
public class ImportBeanApplication {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(ImportBeanApplication.class);
        System.out.println(annotationConfigApplicationContext.getBean(ProductConfig.class));
        System.out.println(annotationConfigApplicationContext.getBean(StoreConfig.class));
    }

}

相关文章:

  • 【CubeMX-HAL库】STM32F407—无刷电机学习笔记
  • openAI最新o1模型 推理能力上表现出色 准确性方面提升 API如何接入?
  • vscode ESP32配置
  • 苍穹外卖项目demo开发day3 公共字段自动填充 增删改查菜品
  • 使用llama.cpp在gpu和cpu上运行deepseek-r1 7b的性能对比
  • 计算机组成原理—— 总线系统(十二)
  • pytest测试专题 - 2.1 一种推荐的测试目录结构
  • 编程速递-庆祝Delphi诞生30周年!
  • 2025智能硬件售后服务管理系统选择的六大标准
  • 小项目第一天
  • CAS单点登录(第7版)20.用户界面
  • Centos安装php-8.0.24.tar
  • unity学习41:动画里的曲线curve参数 和 事件 events
  • CAS单点登录(第7版)17.账户注册
  • 深度学习框架探秘|TensorFlow:AI 世界的万能钥匙
  • 安科瑞光伏发电防逆流解决方案——守护电网安全,提升能源效率
  • 算法随笔_51: 表现良好的最长时间段_方法2
  • Java三大特性
  • Uniapp 短视频去水印解析工具开发实现
  • Ubuntu添加桌面快捷方式
  • 悬疑剧背后的女编剧:创作的差异不在性别,而在经验
  • 美叙领导人25年来首次会面探索关系正常化,特朗普下令解除对叙经济制裁
  • 牛市早报|中美日内瓦经贸会谈联合声明公布
  • 【社论】人工智能将为教育带来什么
  • 水豚“豆包”出逃已40天,扬州茱萸湾景区追加悬赏
  • 上海护师邢红获第50届南丁格尔奖,她为何能摘得护理界最高荣誉