在Apache Commons Configuration中,有PropertiesConfiguration。它支持将分隔符字符串转换为数组/列表的功能。
例如,如果您有一个属性文件:
foo=bar1, bar2, bar3
使用以下代码:
PropertiesConfiguration config = new PropertiesConfiguration("Foo.properties")
String[] values = config.getStringArray("foo")
这将为您提供一个字符串数组["bar1", "bar2", "bar3"]
getString
仅返回多值键的第一个值。尝试使用getStringArray
以获取两个值。
完整代码示例:
ApacheCommonPropertyConfig.java
import java.util.List;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
public class ApacheCommonPropertyConfig {
public static void main(String[] args) throws ConfigurationException {
PropertiesConfiguration config;
try {
config = new PropertiesConfiguration("F://foo.properties");
String[] values = config.getStringArray("foo");
for(String strVal : values) {
System.out.println("Array Value is: "+strVal);
}
List<Object> linclude = config.getList("foo");
for(Object str : linclude){
System.out.println("List Value is: "+str.toString());
}
List<Object> list = config.getList("listOfValue", config.getList("foo"));
for(Object str : list){
System.out.println("Another List Value is: "+str.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
foo.properties
foo=bar1, bar2, bar3
输出:
Array Value is: bar1
Array Value is: bar2
Array Value is: bar3
List Value is: bar1
List Value is: bar2
List Value is: bar3
Another List Value is: bar1
Another List Value is: bar2
Another List Value is: bar3
另一个使用AbstractFileConfiguration的示例
ListDelimiterDemo.java
import org.apache.commons.configuration.AbstractFileConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
public class ListDelimiterDemo {
public static void main(String[] args) throws ConfigurationException {
AbstractFileConfiguration config = new PropertiesConfiguration();
config.setListDelimiter(',');
config.load("F://foo.properties");
for (Object listItem : config.getList("foo")) {
System.out.println(listItem);
}
}
}
输出:
bar1
bar2
bar3
资源链接:
- 从属性文件中读取列表并使用Spring注解@Value加载
- PropertiesConfiguration类
move.patternfile.include = \\*1a.txt, \\*2a.txt.
像这样? - Ravindra Mijar