如何在属性文件中指定值,以便可以使用ResourceBundle#getStringArray检索它们?
我试图使用ResourceBundle#getStringArray
从属性文件中检索String[]
。 文档中对此方法的描述如下:
从此资源包或其父项之一获取给定键的字符串数组。
但是,我试图将属性文件中的值存储为多个单独的键/值对:
key=value1 key=value2 key=value3
并以逗号分隔的列表:
key=value1,value2,value3
但这些都不能使用ResourceBundle#getStringArray
检索。
如何在属性文件中表示一组键/值对,以便可以使用ResourceBundle#getStringArray
检索它们?
Properties
对象可以保存Object
,而不仅仅是String
。 这往往被遗忘,因为它们绝大多数用于加载.properties文件,因此通常只包含String
。 该文档表明调用bundle.getStringArray(key)
等同于调用(String[]) bundle.getObject(key)
。 这就是问题:值不是String[]
,它是一个String
。
我建议以逗号分隔格式存储它并在值上调用split()
。
您可以使用Commons Configuration ,它具有getList
和getStringArray
方法,允许您检索逗号分隔字符串列表。
嗯,看起来这是一个常见的问题,来自这里和这里的线程。
看来要么你不使用这个方法并自己解析一个数组的值,要么你自己编写自己的ResourceBundle实现:(也许有一个apache commons项目…
从JDK源代码来看,PropertyResourceBundle似乎不支持它。
例:
mail.ccEmailAddresses=he@anyserver.at, she@anotherserver.at
..
myBundle=PropertyResourceBundle.getBundle("mailTemplates/bundle-name", _locale);
..
public List getCcEmailAddresses() { List ccEmailAddresses=new ArrayList (); if(this.myBundle.containsKey("mail.ccEmailAddresses")) { ccEmailAddresses.addAll(Arrays.asList(this.template.getString("mail.ccEmailAddresses").split("\\s*(,|\\s)\\s*")));// 1)Zero or more whitespaces (\\s*) 2) comma, or whitespace (,|\\s) 3) Zero or more whitespaces (\\s*) } return ccEmailAddresses; }
我不认为从属性文件加载ResourceBundles可以实现这一点。 PropertyResourceBundle利用Properties类加载属性文件。 Properties类将属性文件作为一组String-> String映射条目加载,并且不支持拉出String []值。
调用ResourceBundle.getStringArray只调用ResourceBundle.getObject,将结果转换为String []。 由于PropertyResourceBundle只是将其移交给从文件加载的Properties实例,因此您永远无法使用当前的库存PropertyResourceBundle。
只需使用spring – Spring .properties文件:将元素作为数组
相关代码:
base.module.elementToSearch=1,2,3,4,5,6 @Value("${base.module.elementToSearch}") private String[] elementToSearch;
key=value1;value2;value3 String[] toArray = rs.getString("key").split(";");
public String[] getPropertyStringArray(PropertyResourceBundle bundle, String keyPrefix) { String[] result; Enumeration keys = bundle.getKeys(); ArrayList temp = new ArrayList (); for (Enumeration e = keys; keys.hasMoreElements();) { String key = e.nextElement(); if (key.startsWith(keyPrefix)) { temp.add(key); } } result = new String[temp.size()]; for (int i = 0; i < temp.size(); i++) { result[i] = bundle.getString(temp.get(i)); } return result; }
我试过这个并找到了办法。 一种方法是定义ListresourceBundle的子类,然后定义String []类型的实例变量并将值赋给键..这里是代码
@Override protected Object[][] getContents() { // TODO Auto-generated method stub String[] str1 = {"L1","L2"}; return new Object[][]{ {"name",str1}, {"country","UK"} }; }