In Apache Commons Configuration, there is PropertiesConfiguration. It supports the feature of
converting delimited string to array/list.
For example, if you have a properties file
#Foo.properties
foo=bar1, bar2, bar3
With the below code:
PropertiesConfiguration config = new PropertiesConfiguration("Foo.properties");
String[] values = config.getStringArray("foo");
will give you a string array of
["bar1", "bar2", "bar3"]
getString
only returns the first value for a multi-value key. Try getStringArray
to get both values.Full Code Example:
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");
// For Array
String[] values = config.getStringArray("foo");
for(String strVal : values) {
System.out.println("Array Value is: "+strVal);
}
// For List
List<Object> linclude = config.getList("foo");
for(Object str : linclude){
System.out.println("List Value is: "+str.toString());
}
// For List Another
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
Output:
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
Another example using 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);
}
}
}
Output:
bar1
bar2
bar3
Resource Link:
- Reading a List from properties file and load with spring annotation @Value
- Class PropertiesConfiguration
Original Link: Read comma separated properties with configuration2 in java
No comments:
Post a Comment