Java Read Property Value as String

Tags: Properties PropertiesUtils

In this Java tutorial, we learn how to implement a Java utility class to load the properties file and read the property value as a String object in Java programming language.

How to get property value as a String in java

For example, we have a the properties file named application.properties located under resources directory in your Java project with the content as below.

src/main/resources/application.properties

appName=Simple Solution

At this step, we create a new Java class named PropertiesUtils.

In this class, implement a static Java code block to load the content of application.properties file into Properties object. And a method named getProperty(String key) to read a single property value String as Java code below.

PropertiesUtils.java

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

public class PropertiesUtils {

    private static final String PROPERTIES_FILE_NAME = "application.properties";

    private static Properties properties;

    /**
     * Load properties file
     */
    static {
        properties = new Properties();
        try(InputStream inputStream = PropertiesUtils.class.getResourceAsStream(PROPERTIES_FILE_NAME)) {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Get property value by key and return as a String
     * @param key the property key
     * @return the property value as a String
     */
    public static String getProperty(String key) {
        return properties.getProperty(key);
    }
}

In the following example Java code, we learn how to use the above PropertiesUtils class to read the property value as a String in Java program.

PropertiesUtilsExample.java

public class PropertiesUtilsExample {
    public static void main(String... args) {
        // Get Property Value as String
        String configValue = PropertiesUtils.getProperty("appName");

        System.out.println(configValue);
    }
}
The output as below.
Simple Solution

Happy Coding 😊

Java Read Property Value as Integer

Java Read Property Value as Long

Java Read Property Value as Double