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!