从Properties中获取int,float,boolean和string

Pra*_*ngh 29 java constants properties-file

我有属性文件中的int,float,boolean和string.所有东西都加载了属性.目前,我正在解析值,因为我知道特定键的预期值.

Boolean.parseBoolean("false");
Integer.parseInt("3")
Run Code Online (Sandbox Code Playgroud)

什么是设置这些常量值的更好方法,如果我不知道键的原始值数据类型是什么.

public class Messages {

    Properties appProperties = null;
    FileInputStream file = null;

    public void initialization() throws Exception {

        appProperties = new Properties();
        try {

            loadPropertiesFile();

        } catch (Exception e) {
            throw new Exception(e.getMessage(), e);
        }
    }

    public void loadPropertiesFile() throws IOException {

        String path = "./cfg/message.properties";
        file = new FileInputStream(path);
        appProperties.load(file);
        file.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

属性文件.messassge.properties

SSO_URL = https://example.com/connect/token
SSO_API_USERNAME = test
SSO_API_PASSWORD = Uo88YmMpKUp
SSO_API_SCOPE = intraday_api
SSO_IS_PROXY_ENABLED = false
SSO_MAX_RETRY_COUNT = 3
SSO_FLOAT_VALUE = 3.0
Run Code Online (Sandbox Code Playgroud)

Constant.java

public class Constants {
    public static String SSO_URL = null;
    public static String SSO_API_USERNAME = null;
    public static String SSO_API_PASSWORD = null;
    public static String SSO_API_SCOPE = null;
    public static boolean SSO_IS_PROXY_ENABLED = false;
    public static int SSO_MAX_RETRY_COUNT = 0;
    public static float SSO_FLOAT_VALUE = 0;
}
Run Code Online (Sandbox Code Playgroud)

And*_*eas 30

如果您有一类配置值(如Constants类),并且要从配置(属性)文件加载所有值,则可以创建一个小助手类并使用反射:

public class ConfigLoader {
    public static void load(Class<?> configClass, String file) {
        try {
            Properties props = new Properties();
            try (FileInputStream propStream = new FileInputStream(file)) {
                props.load(propStream);
            }
            for (Field field : configClass.getDeclaredFields())
                if (Modifier.isStatic(field.getModifiers()))
                    field.set(null, getValue(props, field.getName(), field.getType()));
        } catch (Exception e) {
            throw new RuntimeException("Error loading configuration: " + e, e);
        }
    }
    private static Object getValue(Properties props, String name, Class<?> type) {
        String value = props.getProperty(name);
        if (value == null)
            throw new IllegalArgumentException("Missing configuration value: " + name);
        if (type == String.class)
            return value;
        if (type == boolean.class)
            return Boolean.parseBoolean(value);
        if (type == int.class)
            return Integer.parseInt(value);
        if (type == float.class)
            return Float.parseFloat(value);
        throw new IllegalArgumentException("Unknown configuration value type: " + type.getName());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你这样称呼它:

ConfigLoader.load(Constants.class, "/path/to/constants.properties");
Run Code Online (Sandbox Code Playgroud)

您可以扩展代码以处理更多类型.您也可以将其更改为忽略缺少的属性,而不是像现在那样失败,这样字段声明中的赋值将保持不变,即默认值.

  • @PratiyushKumarSingh你在你的问题中从未提到常数可以是最终的,恕我直言这显然是你迄今为止最好的选择 (2认同)

jos*_*van 5

如果您知道常量的类型,则可以使用Apache Commons Collections.

例如,您可以根据常量的类型使用一些实用程序方法.

booelan SSO_IS_PROXY_ENABLED = MapUtils.getBooleanValue(appProperties, "SSO_IS_PROXY_ENABLED", false);
String SSO_URL = MapUtils.getString(appProperties, "SSO_URL", "https://example.com/connect/token");
Run Code Online (Sandbox Code Playgroud)

您甚至可以使用默认值来避免错误.

  • 是的,如果我们知道原语的数据类型,它工作正常.但我们不能硬编码或编写100个此类属性值的代码. (2认同)
  • @PratiyushKumarSingh为什么你不能硬编码数据类型,当你必须硬编码类型?例如``SSO_URL`被*定义为*String`(硬编码),所以调用`getString()`(匹配硬编码). (2认同)
  • 是的,安德烈亚斯,目前我正在这样做,它看起来不像是优化的解决方案. (2认同)

Ari*_*afa 5

Dambros是对的,你在Properties文件中存储的每个东西都是String值.您可以在检索属性值后跟踪不同的原始数据类型,如下所示. -

Java属性文件:如何在Java中读取config.properties值?

package crunchify.com.tutorial;

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

/**
 * @author Crunchify.com
 * 
 */

public class CrunchifyGetPropertyValues {
    String result = "";
    InputStream inputStream;

    public String getPropValues() throws IOException {

        try {
            Properties prop = new Properties();
            String propFileName = "config.properties";

            inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

            if (inputStream != null) {
                prop.load(inputStream);
            } else {
                throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
            }

            Date time = new Date(System.currentTimeMillis());

            // get the property value and print it out
            String user = prop.getProperty("user");
            String company1 = prop.getProperty("company1");
            String company2 = prop.getProperty("company2");
            String company3 = prop.getProperty("company3");

            result = "Company List = " + company1 + ", " + company2 + ", " + company3;
            System.out.println(result + "\nProgram Ran on " + time + " by user=" + user);
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        } finally {
            inputStream.close();
        }
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后转换为原始 - 如何将String转换为原始类型值?

我建议您通过将键值放在String类型的switch语句中来跟踪数据类型值,然后使用键名称case检索相关的数据类型值.Java 7之后可以使用字符串类型切换案例.

  • 是的,这也是可能的解决方案.查看Dambros建议的想法,我们也可以使用不同的文件来处理原语,如int_message.properties,string_messge.properties ......等等. (3认同)