1 Create folder MyProject/resources/language
2 Create file message_en.properties as below:
Menu.English=English
Menu.Chinese=Chinese
3 Create file message_zh_CN.properties as below:
Menu.English=\u82F1\u8BED
Menu.Chinese=\u4E2D\u6587
4 Create the class
package basic.util.resource;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import basic.util.exception.BaseException;
public class ResourceUtil {
final public static String Message = "language.message";
public static ResourceBundle getResourceBundle() {
try {
return ResourceBundle.getBundle(Message, Locale.getDefault());
} catch (NullPointerException exception) {
BaseException.throwException(BaseException.NotLoaded, exception, "Resource File", Message);
} catch (MissingResourceException exception) {
BaseException.throwException(BaseException.NotFound, exception, Message);
}
return null;
}
public static String getString(String key, String defaultValue, String...parameters) {
ResourceBundle resourceBundle = getResourceBundle();
String formatMessage;
ArrayList<String> paramList = new ArrayList<String>();
try {
MessageFormat format = new MessageFormat(resourceBundle.getString(key));
for (String param : parameters) {
paramList.add(resourceBundle.getString(param));
}
formatMessage = format.format(paramList.toArray(new String[paramList.size()]));
} catch(Exception exception) {
MessageFormat format = new MessageFormat(defaultValue);
formatMessage = format.format(parameters);
}
return formatMessage;
}
public static String getString(String key) {
return getString(key, key);
}
}
No comments:
Post a Comment