Home » Java » java – Unable to use access properties from Properties file in IntelliJ IDEA using Singleton class-Exceptionshub

java – Unable to use access properties from Properties file in IntelliJ IDEA using Singleton class-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I was practicing to access properties from property file using a singleton class called PropertyLoader but however my maven project is not able to locate the file in resources and giving null pointer excepiton.

Here is the class code.

import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;

public class PropertyLoader {
    private static PropertyLoader instance = null;
    private Properties properties;
    private final static Logger LOGGER = Logger.getLogger(PropertyLoader.class.getName());


    protected PropertyLoader() throws IOException {
        //TODO: Fix problem with loading properties file below
        properties = new Properties();
        properties.load(PropertyLoader.class.getResourceAsStream("app.properties"));

    }

    public static PropertyLoader getInstance() {
        if(instance == null) {
            try {
                instance = new PropertyLoader();
            } catch (IOException ioe) {
                LOGGER.error("Error Occurred while creating Property Loader instance: " + ioe.getMessage());
            }
        }
        return instance;
    }

    public String getValue(String key) {
        LOGGER.info("Getting property value for: " + key);
        return properties.getProperty(key);
    }

}

Error I am getting:

Exception in thread “main” java.lang.NullPointerException: inStream
parameter is null at
java.base/java.util.Objects.requireNonNull(Objects.java:247) at
java.base/java.util.Properties.load(Properties.java:404) at
in.net.sudhir.evernote.client.batchjob.PropertyLoader.(PropertyLoader.java:16)
at
in.net.sudhir.evernote.client.batchjob.PropertyLoader.getInstance(PropertyLoader.java:23)
at
in.net.sudhir.evernote.client.batchjob.EvernoteClient.(EvernoteClient.java:51)
at
in.net.sudhir.evernote.client.batchjob.BatchProcess.main(BatchProcess.java:33)

Here is the Screen shot of Project Structure.

Project Structure in IntelliJ IDEA

How to&Answers:
properties = new Properties();

try(InputStream inputStream = PropertyLoader.class.getClassLoader().getResourceAsStream("app.properties")) {
    if(inputStream == null)
        throw new FileNotFoundException("File not found in classpath");

    properties.load(inputStream);
}

NOTE: It’s bad practice to do computations in the constructor. It’s better to create some method that load a resource file.