Java.util.ResourceBundle.getStringArray() 方法
描述
java.util.ResourceBundle.getStringArray(String key) 方法从该资源包或其父资源包中获取给定键的字符串数组。
声明
以下是 java.util.ResourceBundle.getStringArray() 方法的声明
public final String[] getStringArray(String key)
参数
key − 所需字符串数组的键
返回值
此方法返回给定键数组的字符串
异常
NullPointerException − 如果键为 null
MissingResourceException − 如果找不到给定键的对象
ClassCastException − 如果为给定键找到的对象不是字符串
示例
下面的例子展示了 java.util.ResourceBundle.getStringArray() 方法的使用。
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
// this method seems to be having problems with the base implementation
// the following example shows an alternative way doing the same function
public class ResourceBundleDemo {
public static String[] getPropertyStringArray(ResourceBundle bundle, Strin keyPrefix) {
String[] result;
Enumeration<String> keys = bundle.getKeys();
ArrayList<String> temp = new ArrayList<String>();
// get the keys and add them in a temporary ArrayList
for (Enumeration<String> e = keys; keys.hasMoreElements();) {
String key = e.nextElement();
if (key.startsWith(keyPrefix)) {
temp.add(key);
}
}
// create a string array based on the size of temporary ArrayList
result = new String[temp.size()];
// store the bundle Strings in the StringArray
for (int i = 0; i < temp.size(); i++) {
result[i] = bundle.getString(temp.get(i));
}
return result;
}
public static void main(String[] args) {
// create a new ResourceBundle with specified locale
ResourceBundle bundle = ResourceBundle.getBundle("hello", Locale.US);
// save the keys in a string array
String[] s = ResourceBundleDemo.getPropertyStringArray(bundle, "");
// print the string array one by one
for (int i = 0; i < s.length; i++) {
System.out.println("" + s[i]);
}
}
}
假设我们在您的 CLASSPATH 中有一个可用的资源文件 hello_en_US.properties,其内容如下。 该文件将用作我们示例程序的输入 −
hello = Hello World! bye = Goodbye World! morning = Good Morning World!
让我们编译并运行上面的程序,这将产生以下结果 −
Hello World! Goodbye World! Good Morning World!