您的位置:首页 > 编程语言 > Java开发

Java:国际化

2017-01-03 22:15 393 查看
Java的国际化:

资源文件的命名可以有如下三种形式:
baseName _ language _country.properties
baseName _language.properties
baseName.properties
其中baseName是资源文件的基本名,用户可以自由定义。而language和country都不可随意变化,必须是Java所支持的语言和国家。



Java代码:

package org.ah.action;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

public class Test {
public static void main(String[] args) {
// 通过共名访问资源文件,系统会自动匹配当前语言(例如:zh CN)
ResourceBundle rb = ResourceBundle.getBundle("lan");
// 取值
String str1 = rb.getString("msg1");
System.out.println(str1);
// 取值传参,使用MessageFormat.format设置参数数组
String str2 = MessageFormat.format(rb.getString("msg2"), new String[] {
"杰克", "安迪" });
System.out.println(str2);

// 强改国籍
Locale locale2 = new Locale("ja", "JP");
printMsg1(locale2);

Locale locale3 = new Locale("en", "US");
printMsg1(locale3);

// 强改到不存在的国家资源文件,显示当前国家语言
Locale locale4 = new Locale("ko", "KA");
printMsg1(locale4);
// 如果当前国家语言不存在,使用无后缀的资源文件(lan.properties),可以把zh_CN删了再试试
}

private static void printMsg1(Locale locale) {
ResourceBundle rb = ResourceBundle.getBundle("lan", locale);
String str = rb.getString("msg1");
System.out.println(locale.toString() + ":" + str);
}
}


资源文件【放在src下】

lan.properties

msg1=freedom
msg2=hello,{0},I'm{1}


lan_zh_CN.properties

自由
你好,杰克,我是安迪

msg1=\u81EA\u7531
msg2=\u4F60\u597D\uFF0C{0},\u6211\u662F{1}


lan_ja_JP.properties

じゆう

よろしくお願いします,{0},私は{1}です

msg1=\u3058\u3086\u3046
msg2=\u304A\u306F\u3088\u3046\u3054\u3056\u3044\u307E\u3059,{0},\u79C1\u306F{1}\u3067\u3059


lan_en_US.properties

msg1=color
msg2=hello,{0},I'm{1}


运行结果:

自由
你好,杰克,我是安迪
ja_JP:じゆう
en_US:color
ko_KA:自由


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: