NullPointerException when reading a properties file in Java

前端 未结 11 1401
我在风中等你
我在风中等你 2020-12-09 17:05

I am using the following code to read a properties file:

Properties pro = new Properties();
InputStream is = Thread.currentThread().getContextClassLoader().         


        
11条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 17:27

    Bugfixing is easier if you write more lines, like:

    Properties properties = new Properties();
    Thread currentThread = Thread.currentThread();
    ClassLoader contextClassLoader = currentThread.getContextClassLoader();
    InputStream propertiesStream = contextClassLoader.getResourceAsStream("resource.properties");
    if (propertiesStream != null) {
      properties.load(propertiesStream);
      // TODO close the stream
    } else {
      // Properties file not found!
    }
    

提交回复
热议问题