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的值就能动态切换方法了。
相关推荐
兵慌码乱8 小时前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理
金銀銅鐵9 小时前
[Python] 体验用欧几里得算法计算最大公约数的过程
python·数学
FreakStudio13 小时前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
用户03321266636714 小时前
使用 Python 从零创建 Word 文档
python
程序员晓琪14 小时前
约定大于配置:基于 Java 包名自动生成 API 版本路由的最佳实践
java·spring boot·后端
Flittly14 小时前
【AgentScope Java新手村系列】(11)中断与恢复
java·spring boot·spring
Csvn19 小时前
Python 两大经典坑点 —— 可变默认参数 & 闭包延迟绑定
后端·python
曲幽20 小时前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate
用户5569188175321 小时前
#从脚本到独立程序:Python + Playwright 批量抓取的完整踩坑记录
python·自动化运维
兵慌码乱1 天前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2