how to get the values of parameterized variables from a config.properties in java?

1

I have a mvn project, I have the config.properties in the resources and I want to call it in the main

public class GetProperties {
    private Properties prop = new Properties();

    public GetProperties() {

    InputStream in = 
    getClass().getResourceAsStream("/config.properties");


try {
  prop.load(in);
} catch (FileNotFoundException e) {
  System.out.println("The property file was not found");
} catch (IOException e) {
  System.out.println("Can not read property file");
}
}

  public String getPropValues( String propertyName){
  return prop.getProperty(propertyName);
   }
  }

That's my GetProperties class, but it gives me Null Pointer Exception

    
asked by szito 22.01.2018 в 17:46
source

1 answer

1

If you get NullPointerException is because the file is not found, it must be in the root of the project ("/config.properties"). Make sure that the name is the one you have defined: config.properties .

Use ClassLoader as context to use getResourceAsStream()

ClassLoader loader = Thread.currentThread().getContextClassLoader();           
InputStream in = loader.getResourceAsStream("/config.properties");
    
answered by 22.01.2018 / 18:20
source