Java 从属性中获取 int、float、boolean 和 string
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36723839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get int, float, boolean and string from Properties
提问by Pratiyush Kumar Singh
I have int, float, boolean and string from Properties file. Everything has loaded in Properties. Currently, I am parsing values as I know expected value for particular key.
我有属性文件中的 int、float、boolean 和 string。一切都已加载到属性中。目前,我正在解析值,因为我知道特定键的预期值。
Boolean.parseBoolean("false");
Integer.parseInt("3")
What is better way of setting these constants values, If I don't know what could be primitive value datatype for a key.
设置这些常量值的更好方法是什么,如果我不知道键的原始值数据类型是什么。
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();
}
}
Properties File. 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
Constant.java
常量.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;
}
采纳答案by Andreas
If you have a class of configuration values, like your Constants
class, and you want to load all values from a configuration (properties) file, you can create a little helper class and use reflection:
如果您有一类配置值,例如您的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());
}
}
Then you call it like this:
然后你这样称呼它:
ConfigLoader.load(Constants.class, "/path/to/constants.properties");
You can extend the code to handle more types. You can also change it to ignore missing properties, instead of failing like it does now, such that assignments in the field declaration will remain unchanged, i.e. be the default.
您可以扩展代码以处理更多类型。您还可以更改它以忽略缺少的属性,而不是像现在那样失败,这样字段声明中的分配将保持不变,即成为默认值。
回答by josivan
If you know the type of constant, you can use Apache Commons Collections.
如果您知道常量的类型,则可以使用Apache Commons Collections。
For example, you can use some utilities method based on type of your constant.
例如,您可以根据常量的类型使用一些实用程序方法。
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");
You can even use default values to avoid errors.
您甚至可以使用默认值来避免错误。
回答by ArifMustafa
Dambros is right, every thing you store inside a Properties file is as a String value. You can track your different primitive data types after retrieving properties value as below like ref. -
Dambros 是对的,你存储在 Properties 文件中的每件事都是作为一个 String 值。您可以在检索属性值后跟踪不同的原始数据类型,如下所示。——
Java Properties File: How to Read config.properties Values in Java?
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;
}
}
and later convert to primitive - How to convert String to primitive type value?
然后转换为原始类型 - 如何将字符串转换为原始类型值?
I suggest you to track your data types value by putting the key values inside String type switch statement and later retrieve the related data type value by using key name cases. String type switch case is possible after Java 7.
我建议您通过将键值放在 String 类型 switch 语句中来跟踪数据类型值,然后使用键名大小写检索相关数据类型值。在 Java 7 之后可以使用字符串类型 switch case。
回答by uniknow
Not entirely sure whether I exactly understand the problem but a possibility could be to include the type of the property value in the (String) value. So for example the properties you showed would become something like:
不完全确定我是否完全理解问题,但有可能在 (String) 值中包含属性值的类型。例如,您显示的属性将变为:
SSO_URL = URL:https://example.com/connect/token
SSO_API_USERNAME = STRING:test
SSO_API_PASSWORD = STRING:Uo88YmMpKUp
SSO_API_SCOPE = STRING:intraday_api
SSO_IS_PROXY_ENABLED = BOOLEAN:false
SSO_MAX_RETRY_COUNT = INTEGER:3
SSO_FLOAT_VALUE = FLOAT:3.0
During the parsing of the property values you first determine the type of the property by looking at the part before :
and use the part after for the actual parsing.
在解析属性值期间,您首先通过查看之前的部分:
并使用之后的部分进行实际解析来确定属性的类型。
private static Object getValue(Properties props, String name) {
String propertyValue = props.getProperty(name);
if (propertyValue == null) {
throw new IllegalArgumentException("Missing configuration value: " + name);
} else {
String[] parts = string.split(":");
switch(parts[0]) {
case "STRING":
return parts[1];
case "BOOLEAN":
return Boolean.parseBoolean(parts[1]);
....
default:
throw new IllegalArgumentException("Unknown configuration value type: " + parts[0]);
}
}
}
回答by Andrew Kolpakov
Spring Boot has ready to use and feature reach solution for type-safe configurationproperties.
Spring Boot 已经准备好使用类型安全配置属性的功能到达解决方案。
Definitely, use of the Spring just for this task is overkill but Spring has a lot of cool features and this one can attract you to right side ;)
当然,仅将 Spring 用于此任务是过大的,但 Spring 有很多很酷的功能,而这个功能可以吸引您到右侧;)
回答by Carlos Herrera
Follow the dropwizard configuration pattern where you define your constants using YAML instead of Properties and use Hymanson to deserialize it into your Class. Other than type safety, dropwizard's configuration pattern goes one step further by allowing Hibernate Validator annotations to validate that the values fall into your expected ranges.
遵循 dropwizard 配置模式,使用 YAML 而不是 Properties 定义常量,并使用 Hymanson 将其反序列化到您的类中。除了类型安全之外,dropwizard 的配置模式更进一步,允许 Hibernate Validator 注释来验证值是否落入您的预期范围。
For dropwizard's example...
对于 dropwizard 的例子...
For more information about the technology involved...
有关所涉及技术的更多信息...
- github.com/FasterXML/Hymanson-dataformat-yaml
- hibernate.org/validator/
- github.com/FasterXML/Hymanson-dataformat-yaml
- hibernate.org/validator/
回答by Alicia
You can define your configurable parameters as 'static' in your class of choice, and from a static init call a method that loads the parameter values from a properties file.
您可以在您选择的类中将可配置参数定义为“静态”,并从静态初始化调用一个从属性文件加载参数值的方法。
For example:
例如:
public class MyAppConfig {
final static String propertiesPath="/home/workspace/MyApp/src/config.properties";
static String strParam;
static boolean boolParam;
static int intParam;
static double dblParam;
static {
// Other static initialization tasks...
loadParams();
}
private static void loadParams(){
Properties prop = new Properties();
try (InputStream propStream=new FileInputStream(propertiesPath)){
// Load parameters from config file
prop.load(propStream);
// Second param is default value in case key-pair is missing
strParam=prop.getProperty("StrParam", "foo");
boolParam=Boolean.parseBoolean(prop.getProperty("boolParam", "false"));
intParam= Integer.parseInt(prop.getProperty("intParam", "1"));
dblParam=Double.parseDouble(prop.getProperty("dblParam", "0.05"));
} catch (IOException e) {
logger.severe(e.getMessage());
e.printStackTrace();
}
}
}