SpringBoot项目中读取resource目录下的文件(六种方法)

文章目录

一、先获取绝对路径再读取文件(jar包里会获取不到)

方法一:类加载器的getResource().getPath()获取目录路径
复制代码
    /**
     * 方法一:使用类加载器的getResource().getPath()获取全路径再拼接文件名,最后根据文件路径获取文件流
     * 备注:jar包不可用,因为jar包中没有一个实际的路径存放文件
     *
     * @param fileName
     * @return
     * @throws FileNotFoundException
     */
    public BufferedReader function1(String fileName) throws FileNotFoundException {

        //   /Users//code/read-resource/target/classes/
        String path = this.getClass().getClassLoader().getResource("").getPath();
        //   /Users//code/read-resource/target/classes/测试.txt
        String filePath = path + fileName;

        return new BufferedReader(new FileReader(filePath));
    }
方法二:类加载器的getResource().getPath()获取文件路径
复制代码
    /**
     * 方法二:使用类加载器的getResource().getPath(),传参直接获取文件路径,再根据文件路径获取文件流
     * 备注:jar包不可用,因为jar包中没有一个实际的路径存放文件
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public BufferedReader function2(String fileName) throws IOException {

        //   /Users//code/read-resource/target/classes/%e6%b5%8b%e8%af%95.txt
        String filePath = this.getClass().getClassLoader().getResource(fileName).getPath();

        //可以看到上面读取到路径的中文被URLEncoder编码了,所以需要先用URLDecoder解码一下,恢复中文
        filePath = URLDecoder.decode(filePath, "UTF-8");

        return new BufferedReader(new FileReader(filePath));
    }

二、直接获取文件流(jar包可用)

方法三:ClassLoader对象的getResourceAsStream()
复制代码
    /**
     * 方法三:使用类加载器的getResourceAsStream(),直接获取文件流
     * 备注:jar包可用
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public BufferedReader function3(String fileName) throws IOException {
        //getResourceAsStream(fileName) 等价于getResource(fileName).openStream()
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
        if (inputStream == null) {
            throw new FileNotFoundException(fileName);
        }
        return new BufferedReader(new InputStreamReader(inputStream));
    }
方法四:Class对象的getResourceAsStream()
  1. ClassLoader 的getResource()是从类路径的根路径查找的,所以不加"/"也可以

  2. Class 的getResource()是从当前类所在的包路径查找资源,所以如果不加"/"表示去根路径查找的话,是找不到的

    复制代码
    /**
     * 方法四:使用Class对象的getResourceAsStream()获取文件流
     * 备注:jar包可用
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public BufferedReader function4(String fileName) throws IOException {
        //getResourceAsStream(fileName) 等价于getResource(fileName).openStream()
        InputStream inputStream = this.getClass().getResourceAsStream("/" + fileName);
        if (inputStream == null) {
            throw new FileNotFoundException(fileName);
        }
        return new BufferedReader(new InputStreamReader(inputStream));
    }

三、使用封装好的类(jar包可用)

源码里还是方法三、方法四,只不过做了一些封装,更方便开发

方法五:Spring提供的ClassPathResource
复制代码
    /**
     * 方法五:使用Spring提供的ClassPathResource获取
     * 备注:jar包可用
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public BufferedReader function5(String fileName) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource(fileName);
        InputStream inputStream = classPathResource.getInputStream();
        return new BufferedReader(new InputStreamReader(inputStream));
    }
方法六:Hutool提供的ResourceUtil
复制代码
    /**
     * 方法六:使用Hutool的ResourceUtil
     * 备注:jar包可用
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public BufferedReader function6(String fileName) throws IOException {
        List<URL> resources = ResourceUtil.getResources(fileName);
        URL resource = resources.get(0);
        return new BufferedReader(new InputStreamReader(resource.openStream()));
    }

四、测试jar包中是否可用的代码

1)编写接口

复制代码
   //Jar包启动时根据传入的不同funcation值来选择调用哪个方法测试
    @Value("${function}")
    private int function;    


    @GetMapping("/test")
    public String test() throws IOException {
        //需要在resource里读取的文件
        String fileName = "测试.txt";

        //调用方法
        System.out.println("调用function" + function);
        BufferedReader bufferedReader = null;
        switch (function) {
            case 1:
                bufferedReader = function1(fileName);
                break;
            case 2:
                bufferedReader = function2(fileName);
                break;
            case 3:
                bufferedReader = function3(fileName);
                break;
            case 4:
                bufferedReader = function4(fileName);
                break;
            case 5:
                bufferedReader = function5(fileName);
                break;
            case 6:
                bufferedReader = function6(fileName);
                break;
            default:
        }

        //读取并输出
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line).append("
");
        }
        System.out.println(sb);
        return sb.toString();
    }

2)启动jar包指令

java -jar -Dfunction=6 read-resource-1.0-SNAPSHOT.jar

  • 更改-Dfunction=6的值就能动态切换方法了。
相关推荐
小草cys19 分钟前
NVIDIA 驱动(550版本)成功安装后安装支持 GPU 加速的 PyTorch
人工智能·pytorch·python
SilentSamsara23 分钟前
Python 微服务全链路:gRPC + 链路追踪 + 服务网格接入
开发语言·分布式·python·微服务·架构
Cloud_Shy61843 分钟前
解读《Effective Python 3rd Edition》:从练气到老魔(第三章 Item 21 - 24)
开发语言·人工智能·笔记·python·迭代器模式
张高兴2 小时前
张高兴的 Hailo-10 开发指南:(二)使用 LangChain 搭建本地大模型 RAG 问答应用
python·边缘计算·hailo
财经资讯数据_灵砚智能2 小时前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年6月6日
大数据·人工智能·python·ai·信息可视化·自然语言处理·灵砚智能
Land03293 小时前
Python + RPA 双引擎实战:从手写脚本到可交付自动化应用的完整链路
python·自动化·rpa
菜到离谱但坚持3 小时前
【小白零基础】RAG+LangChain 搭建私有知识库问答系统(完整可运行代码+超详细教程+避坑指南)
python·langchain·rag
ss2733 小时前
【入门OJ题解】分苹果问题(Python/Java/C 实现)
java·c语言·python
IsJunJianXin3 小时前
谷歌搜索cookie NID逆向生成
开发语言·python·google搜索·sgss·nid-cookie·算法生成nid·google-cookie
暗夜猎手-大魔王3 小时前
转载--Hermes Agent 11 | 智能审批与平台化安全:当 AI 来守护 AI
人工智能·python·安全