springboot读取classpath目录下文件

本文介绍了如何在SpringBoot中正确读取src/main/resources目录下的information.txt文件。当项目在Linux环境下运行时,由于文件位于jar内部,直接访问会报错。解决办法是利用ClassPathResource的getInputStream方法来获取InputStream进行读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假设静态资源文件 information.txt 放在 src/main/resources 目录下

 public String getInfo() {
        String msg = "";
        InputStreamReader intput = null;
        try {
            Resource resource = new ClassPathResource("information.txt");
            File file = resource.getFile();
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            msg = reader.readLine();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    return msg;
}

注意:

如果将该项目打包运行在Linux系统下,该方法无法读取文件,报错信息为cannot be resolved to absolute file path because it does not reside in the file system。这是因为在Linux系统下,spring无法访问jar中的路径。

解决方法:

使用ClassPathResource类的getInputStream方法获取InputStream

Linux读取resources目录下文件:

 public String getInfo() {
        String msg = "";
        InputStreamReader intput = null;
        try {
            Resource resource = new ClassPathResource("information.txt");
            // 修改部分
            intput = new InputStreamReader(resource.getInputStream());		
            BufferedReader reader = new BufferedReader(intput);
            msg=  reader.readLine();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    return msg;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值