Convert Properties File To java.util.Map

A sample piece of code used to load the data in a properties file in a java.util.Map

package com.davidking.principles;

import org.junit.Test;

import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import static org.junit.Assert.assertEquals;

 * DynamicMethodInvocationTest
 * User: David King,
 * Date: 5/12/13
 * Time: 7:28 PM
public class DynamicMethodInvocationTest {
    private Logger log = Logger.getLogger(DynamicMethodInvocationTest.class.getName());

    public void testBuildMethodMappings() {
        String methodToInvoke = getMethodToInvoke("get_user");
        assertEquals("GetUserById", methodToInvoke);
        log.log(Level.INFO, "Method to invoke is - {0}", methodToInvoke);

    private String getMethodToInvoke(String requestMethodName) {
        Properties properties = new Properties();
        try {
        } catch (IOException e) {

        log.log(Level.INFO, "properties loaded with this data - {0} ", properties);

        Map<String, Object> mappings = new ConcurrentHashMap<String, Object>();

        Enumeration elements = properties.propertyNames();
        while(elements.hasMoreElements()) {
            String keyProps = (String)elements.nextElement();
            String valProps = properties.getProperty(keyProps);

            // populate the Map
            mappings.put(keyProps, valProps);

        if (mappings.containsKey(requestMethodName)) {
            return mappings.get(requestMethodName).toString();
        return null;

NOTE: The property file is in a package…

The properties file contents are as follows:

# Map action names to proper method names to invoke

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s