java.util.ResourceBundle.getStringArray()方法实例
java.util.ResourceBundle.getStringArray(String key) 方法获取一个字符串数组给定键从此资源包或它的某个父。
声明
以下是java.util.ResourceBundle.getStringArray()方法的声明
public final String[] getStringArray(String key)
参数
-
key -- 所需字符串数组的键
返回值
此方法返回字符串给定键的数组
异常
-
NullPointerException -- 如果 key 是 null
-
MissingResourceException -- 如果找不到给定键对应的对象
-
ClassCastException -- 如果发现给定键的对象不是一个字符串
例子
下面的示例演示java.util.ResourceBundle.getStringArray()方法的用法。
package com.yiibai; 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, String 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!