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

版权声明:商业用途请联系博主,非商业转载请标明出处。 https://blog.csdn.net/qq_15807167/article/details/81782666

问题

  • 问题出现的代码
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找不到路径的问题。

猜你喜欢

转载自blog.csdn.net/qq_15807167/article/details/81782666