How to read resource bundle in java?
BundleTest.java
package org.metadata.core.xml;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class BundleTest {
private ResourceBundle bundle;
public BundleTest() {
bundle = ResourceBundle.getBundle("messages");
}
public String getMessage(String id, Object... params) {
String text = null;
try {
text = bundle.getString(id);
} catch (MissingResourceException e) {
text = "!! key " + id + " not found !!";
}
if (params != null) {
MessageFormat mf = new MessageFormat(text);
text = mf.format(params, new StringBuffer(), null).toString();
}
return text;
}
public static void main(String[] args) {
BundleTest test = new BundleTest();
String message_1 = test.getMessage("MESSAGE_ONE");
System.out.println(message_1);
String message_2 = test.getMessage("MESSAGE_TWO", "ZTO", "Myanmar");
System.out.println(message_2);
}
}
|
- Create a folder name with “resources” and set the folder into the classpath.
- Put the “messages.properties” file into the “resources” folder.
messages.properties
MESSAGE_ONE = Hello World!
MESSAGE_TWO = Hi {0}! Welcome from {1}!
|
Output
Hello World!
Hi ZTO! Welcome from Myanmar!
|
No comments:
Post a Comment