Resource bundle is used for multi language support. If your application/web site provide language support to user, to do this you can do this with resource bundle. In summery, you define a file with same pre-name and post-locale for your supporting langugage. According to your locale, related file's property string will come your program. If your property string not exist in local definition file, it looks default file. If defalt file contains that property, its value shown.
Not: Resource bundle is used only read, not write.
File structure is:
-ResourceBundleExample.java
=== application.properties ====
greet=hello (default)
bye=bye bye (default)
Not: Resource bundle is used only read, not write.
File structure is:
-JavaResourceBundleExample
-src/main/resources
-application_en.properties
-application_tr.properties
-application.properties
-application_tr.properties
-application.properties
-src/main/java
-com.example-ResourceBundleExample.java
a. ResourceBundleExample.java
package com.example; import java.util.Locale; import java.util.ResourceBundle; public class ResourceBundleExample { private static final String FILE_NAME = "application"; public static void main( String[] args ) { ResourceBundle resourceBundle = ResourceBundle.getBundle(FILE_NAME); //default is en System.out.println("default greet: " + resourceBundle.getString("greet")); resourceBundle = ResourceBundle.getBundle(FILE_NAME, new Locale("tr")); System.out.println("tr greet: " + resourceBundle.getString("greet")); resourceBundle = ResourceBundle.getBundle(FILE_NAME, new Locale("en")); System.out.println("en greet: " + resourceBundle.getString("greet")); //There is no property for 'fr', it look for first 'application_en.properties' //'application_en.properties' also not contain 'bye', it look default file(application.properties' resourceBundle = ResourceBundle.getBundle(FILE_NAME, new Locale("fr")); System.out.println("fr greet: " + resourceBundle.getString("greet") ); System.out.println("fr bye: " + resourceBundle.getString("bye")); } }
Output is:
default greet: hello(en) tr greet: merhaba en greet: hello(en) fr greet: hello(en) fr bye: bye bye (default)
b. Resources files:
=== application_en.properties ===
greet=hello(en)
=== application_tr.properties ===
greet=merhaba
greet=hello(en)
=== application_tr.properties ===
greet=merhaba
=== application.properties ====
greet=hello (default)
bye=bye bye (default)