Java Read Property Value as Long

Tags: Properties PropertiesUtils

In this Java tutorial, we learn how to load the properties file and read property value as a Long value in Java programming language.

How to get property value as a Long 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

sampleConfig=112233445566778899

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

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

And then implement the getLong(String key) static method to get the property value and return it as a Long 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 the property value and return as a Long value.
     * @param key the property key.
     * @return the property value as a Long value.
     */
    public static Long getLong(String key) {
        String value = properties.getProperty(key);
        try {
            return Long.valueOf(value);
        } catch (NumberFormatException e){
            return  0L;
        }
    }

}

In the following example Java code, we learn how to use the above PropertiesUtils.getLong() static method to get property value as a Long value in Java program.

PropertiesUtilsExample.java

public class PropertiesUtilsExample {
    public static void main(String... args) {
        // Read Property Value as Long
        Long configValue = PropertiesUtils.getLong("sampleConfig");

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

Happy Coding 😊

Java Read Property Value as String

Java Read Property Value as Integer

Java Read Property Value as Double