Search code examples
javamavenpropertiesproperties-file

Property file is not found and throwing exception?


I am trying to read properties file to fetch the values. But, the code is throwing an exception.

Exception

Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.cisco.installbase.hiveconnector.ReadProperties.getInstance(ReadProperties.java:28)
    at com.cisco.installbase.hiveconnector.MainApp.main(MainApp.java:7)
Caused by: java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:434)
    at java.util.Properties.load0(Properties.java:353)
    at java.util.Properties.load(Properties.java:341)
    at com.cisco.installbase.hiveconnector.ReadProperties.<init>(ReadProperties.java:16)
    at com.cisco.installbase.hiveconnector.ReadProperties.<init>(ReadProperties.java:12)
    at com.cisco.installbase.hiveconnector.ReadProperties$PropHolder.<clinit>(ReadProperties.java:23)
    ... 2 more

ReadProperties.java

package com.cisco.installbase.hiveconnector;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

public class ReadProperties {

    private final Properties props = new Properties();

    private ReadProperties()
    {
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("config.properties");
        try{
            props.load(in);
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    private static class PropHolder{
        private static final ReadProperties INSTANCE = new ReadProperties();
    }

    public static ReadProperties getInstance()
    {
        return PropHolder.INSTANCE;
    }

    public String getProperty(String key)
    {
        return props.getProperty(key);
    }

    public Set<String> getAllPropertyNames()
    {
        return props.stringPropertyNames();
    }

    public boolean containsKey(String key)
    {
        return props.containsKey(key);
    }
}

the directory structure and location of my prop file

enter image description here

Can someone help me with the location where the property file needs to be put.


Solution

  • Your file config.properties is not on classpath, therefore cannot be loaded via this.getClass().getClassLoader().getResourceAsStream("config.properties")

    Put it under src/main/resources

    Please consult the Standard Maven directory layout