Java PropertiesFileReader Utility Class

This post gives you PropertiesFileReader utility class to use in your Java/Java EE projects. You can use this PropertiesFileReader utility class to load "config.properties" file and it provides getValue() API to retrieve a property value by key. 
This is a common task for a developer to maintain project configuration data or settings in an external file, for example keeping JDBC database configurations or mail configurations in the config.properties file. 

PropertiesFileReader.java

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

/**
 * @author Ramesh Fadatare
 *
 */
public class PropertiesFileReader {
    private static Properties prop = null;
    private static final String propFileName = "config.properties";

    private static void loadPropValues() throws IOException {
        prop = new Properties();
        InputStream inputStream = PropertiesFileReader.class.getClassLoader().getResourceAsStream(propFileName);
        prop.load(inputStream);
        if (inputStream == null) {
            throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
        }
    }

    public static String getValue(String key) throws IOException {
        if (prop == null) {
            loadPropValues();
        }
        return prop.getProperty(key);
    }

    public static String getValue(String key, String defaultvalue) throws IOException {
        if (prop == null) {
            loadPropValues();
        }
        return prop.getProperty(key, defaultvalue);
    }
}

Comments