Java resourcebundle
In Java, the ResourceBundle class is used for internationalizing applications by providing localized resources for different languages and regions. The ResourceBundle class is part of the java.util package, and provides a way to load and access resources for a specific locale.
A resource bundle is a collection of properties files that contain key-value pairs for messages, labels, and other localized resources. Each properties file corresponds to a specific locale, and contains the localized values for the keys in the default properties file.
Here's an example of a properties file that contains some key-value pairs for a specific locale:
# Sample ResourceBundle file for the US locale greeting = Hello farewell = Goodbye
To access the values in a resource bundle, you can use the static getBundle()
method of the ResourceBundle class. This method takes the base name of the properties file (without the locale part), and the locale for which to load the properties.
Here's an example that demonstrates how to use the ResourceBundle class to load a resource bundle for the US locale, and retrieve a message from it:
import java.util.*; public class ResourceBundleDemo { public static void main(String[] args) { Locale locale = new Locale("en", "US"); ResourceBundle bundle = ResourceBundle.getBundle("myapp.resources.messages", locale); String greeting = bundle.getString("greeting"); System.out.println(greeting); } }
In this example, a resource bundle for the US locale is loaded from a properties file named myapp/resources/messages_en_US.properties
. The getString()
method is used to retrieve the value for the key "greeting"
from the resource bundle, which is "Hello"
. The output of this code is:
Hello
The ResourceBundle class also provides a way to fall back to a default locale if a specific locale is not available. This can be useful to provide a fallback language or region when a resource is missing.
In summary, the ResourceBundle class in Java provides a way to internationalize applications by providing localized resources for different languages and regions. By using the ResourceBundle class, developers can create software applications that support different languages and regions, and that provide a localized user experience for users from different cultures.