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.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!