SpringBoot--代码方式读取properties出现异常解决

问题

  • 问题出现的代码
String ss = Objects.requireNonNull(app.getClass().getClassLoader().getResource(config.properties")).getPath();
        System.out.println("当前获取的地址为: " + ss);
        try {
            FileSystemResource fileInputStream = new FileSystemResource(new File(ss));
            //
            Properties properties = new Properties();
            properties.load(fileInputStream.getInputStream());
            String property = properties.getProperty("test");

            System.out.println("获取其值: " + property);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

问题原因: 在文件存在的情况下,可以读取到文件路径,但是fileInputStream.getInputStream()会出现找不到文件的情况,在翻阅底层并没什么收获,底层是native的方法,看不到原因(猜测是 路径中带不能识别的字符)

更改为如下代码

InputStream inputStream = Objects.requireNonNull(app.getClass().getClassLoader().getResourceAsStream("config.properties"));
        try {
            //
            Properties properties = new Properties();
            properties.load(inputStream);
            String property = properties.getProperty("test");

            System.out.println("获取其值: " + property);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

getResourceAsStream方法会获取到路径url后从URLStreamHandler建立的链接中获取到流。这样就不会存在上面fileInputStream找不到路径的问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值