Java.util.ResourceBundle.getStringArray() Method



Description

The java.util.ResourceBundle.getStringArray(String key) method gets a string array for the given key from this resource bundle or one of its parents.

Declaration

Following is the declaration for java.util.ResourceBundle.getStringArray() method

public final String[] getStringArray(String key)

Parameters

key − the key for the desired string array

Return Value

This method returns the string for the given key array

Exception

  • NullPointerException − if key is null

  • MissingResourceException − if no object for the given key can be found

  • ClassCastException − if the object found for the given key is not a string

Example

The following example shows the usage of java.util.ResourceBundle.getStringArray() method.

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]);
      }
   }
}

Assuming we have a resource file hello_en_US.properties available in your CLASSPATH, with the following content. This file will be used as an input for our example program −

hello = Hello World!
bye = Goodbye World!
morning = Good Morning World!

Let us compile and run the above program, this will produce the following result −

Hello World!
Goodbye World!
Good Morning World!
java_util_resourcebundle.htm
Advertisements