Java Read Property Value as Integer

Tags: Properties PropertiesUtils

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

How to get property value as an Integer value in Java

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

src/main/resources/application.properties

settingNumber=1107

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

In this new class, implement a static Java code block to load the application.properties file into Properties object.

And implement a new static method named getInteger(String key) to read the property value by given key and convert it from String to Integer value 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 a property value and return as an Integer value.
     * @param key the property key.
     * @return the property value as an Integer.
     */
    public static Integer getInteger(String key) {
        String value = properties.getProperty(key);
        try {
            return Integer.valueOf(value);
        } catch (NumberFormatException e){
            return  0;
        }
    }
}

In the following example Java code, we learn how to use the PropertiesUtils.getInteger() static method above to read property value as an Integer value in Java program.

PropertiesUtilsExample.java

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

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

Happy Coding 😊

Java Read Property Value as String

Java Read Property Value as Long

Java Read Property Value as Double