Java ResourceBundle.getString(String key) method example

In this tutorial, You will learn how to get a string for the given key from this resource bundle using locale. Java ResourceBundle.getString(String key) method returns the string for the given key.

Gets a string for the given key from this resource bundle or one of its parents.

syntax

public final String getString(String key)

Parameters

key - the key for the desired string.

Returns

The string for the given key.

Throws

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.

Java ResourceBundle getString(String key) example

  • Locale.setDefault(new Locale("en", "US")); Construct a locale from language as english and country as US.
  • ResourceBundle.getBundle("configuration"); Get a resource bundle using the base name as "configuration".
  • Locale.getDefault(); Get the current value of the default locale.
  • bundle.getString("greeting"); Get a string for the key "greeting" from this resource bundle.
  • In this example, we have defined two resource bundles "configuration_en_US" and "configuration_en_IN".
package com.technicalkeeda;

import java.util.Locale;
import java.util.ResourceBundle;

public class App {

    public static void main(String[] args) {

        Locale.setDefault(new Locale("en", "US"));
        ResourceBundle bundle = ResourceBundle.getBundle("configuration");
        System.out.println("Message in " + Locale.getDefault() + " :- " + bundle.getString("greeting"));

        Locale.setDefault(new Locale("en", "IN"));
        bundle = ResourceBundle.getBundle("configuration");
        System.out.println("Message in " + Locale.getDefault() + " :- " + bundle.getString("greeting"));
    }
}

Resource bundle files

In this example, we have created two files :-

  • configuration_en_US.properties, It's location is /src/main/resources/configuration_en_US.properties
  • configuration_en_IN.properties, It's location is /src/main/resources/configuration_en_IN.properties

Contents of configuration_en_US.properties

greeting=Hello.

Contents of configuration_en_IN.properties

greeting=Namaste.

output

Message in en_US :- Hello.
Message in en_IN :- Namaste.