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

}
相关推荐
一点程序15 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
C雨后彩虹15 小时前
计算疫情扩散时间
java·数据结构·算法·华为·面试
2601_9498095915 小时前
flutter_for_openharmony家庭相册app实战+我的Tab实现
java·javascript·flutter
vx_BS8133016 小时前
【直接可用源码免费送】计算机毕业设计精选项目03574基于Python的网上商城管理系统设计与实现:Java/PHP/Python/C#小程序、单片机、成品+文档源码支持定制
java·python·课程设计
2601_9498683616 小时前
Flutter for OpenHarmony 电子合同签署App实战 - 已签合同实现
java·开发语言·flutter
达文汐16 小时前
【困难】力扣算法题解析LeetCode332:重新安排行程
java·数据结构·经验分享·算法·leetcode·力扣
培风图南以星河揽胜16 小时前
Java版LeetCode热题100之零钱兑换:动态规划经典问题深度解析
java·leetcode·动态规划
启山智软17 小时前
【中大企业选择源码部署商城系统】
java·spring·商城开发
我真的是大笨蛋17 小时前
深度解析InnoDB如何保障Buffer与磁盘数据一致性
java·数据库·sql·mysql·性能优化
奋进的芋圆17 小时前
Spring Boot 实现三模安全登录:微信扫码 + 手机号验证码 + 邮箱验证码
spring boot·redis·微信