Java Utility Library

Java ResourceBundle - getString() Method



The java.util.ResourceBundle.getString() method is used to get a string for the given key from this resource bundle or one of its parents.

Syntax

public final String getString(String key)

Parameters

key Specify the key for the desired string.

Return Value

Returns the string for the given key.

Exception

  • Throws NullPointerException, if key is null.
  • Throws MissingResourceException, if no object for the given key can be found.
  • Throws ClassCastException, if the object found for the given key is not a string.

Example:

Lets assume that we have resource file called Greetings_en_US.properties in the CLASSPATH with the following content. This file contains local message for US country.

greet = Hello World!

In the below Java program, the java.util.ResourceBundle.getString() method is used to get the string for the given key from the above mentioned resource bundle Greetings_en_US.properties.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a resource bundle in specified locale
    ResourceBundle bundle = ResourceBundle.getBundle("Greetings", Locale.US);

    //printing the text assigned to "greet" 
    //key in the bundle
    System.out.println(bundle.getString("greet"));   
  }
}

The output of the above code will be:

Hello World!

❮ Java.util - ResourceBundle