学习笔记:资源国际化

固定文本的国际化

对于软件中的菜单栏、导航条、错误提示信息,状态信息等这些固定不变的文本信息,可以把它们写在一个properties文件中,并根据不同的国家编写不同的properties文件。这一组properties文件称之为一个资源包

JavaAPI中提供了一个ResourceBundle 类用于描述一个资源包,并且 ResourceBundle类提供了相应的方法getBundle,这个方法可以根据来访者的国家地区自动获取与之对应的资源文件予以显示。

一个资源包中的每个资源文件都必须拥有共同的基名。除了基名,每个资源文件的名称中还必须有标识其本地信息的附加部分。例如:一个资源包的基名是“myproperties”,则与中文、英文环境相对应的资源文件名则为: 
“myproperites_zh.properties”  “myproperites_en.properties”

例如:下面三个资源文件

myproperties.properties写入
username=username 
password=password

myproperties_zh.properties写入
username=\u7528\u6237\u540D //用户名
password=\u5BC6\u7801		//密码

myproperties_en.properties写入
username=username
password=password
main中:

ResourceBundle bundle = ResourceBundle.getBundle("cn.tanc.resource.myproperties",Locale.CHINA);
//ResourceBundle bundle = ResourceBundle.getBundle("cn.tanc.resource.myproperties",Locale.US); 

String username = bundle.getString("username");
String password= bundle.getString("password");

System.out.println(username);
System.out.println(password);
就实现了固定文本的国际化

动态数据的国际化

数值,货币,时间,日期等数据由于可能在程序运行时动态产生,所以无法像文字一样简单地将它们从应用程序中分离出来,而是需要特殊处理。Java 中提供了解决这些问题的 API 类(位于 java.util 包和 java.text 包中)

NumberFormat

Date date = new Date();
DateFormat dateformat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, Locale.CHINA);
String result = dateformat.format(date);
System.out.println(result);

String source = "91-12-7 上午10时25分39秒 GMT";
date = dateformat.parse(source);
System.out.println(date);

DateFormat

getNumberInstance(Locale locale)//多种用途
getIntegerInstance(Locale locale)//处理整数
getCurrencyInstance(Locale locale)//处理货币***
getPercentInstance(Locale locale)//百分比
//同样有 format prase 方法


MessageFormat


结合固态文本,资源文件

myproperties.properties写入
message="on {0,Date}, i spent {1} on this book."

myproperties_zh.properties写入
message="\u5728{0,Date,SHORT}\uFF0C\u6211\u4E70\u8FD9\u672C\u4E66\u82B1\u4E86{1}\u3002"

myproperties_en.properties写入
message="on {0,Date}, i spent {1} on this book."


main

ResourceBundle bundle = ResourceBundle.getBundle("cn.tanc.resource.myproperties", Locale.CHINA);
//ResourceBundle bundle = ResourceBundle.getBundle("cn.tanc.resource.myproperties", Locale.US);

String pattern = bundle.getString("message");
MessageFormat format = new MessageFormat(pattern,Locale.CHINA);
//MessageFormat format = new MessageFormat(pattern,Locale.US);

Object obj[] = {new Date(),99};
String result = format.format(obj);
System.out.println(result);

可以得到

"在13-11-4,我买这本书花了99。"
"on Nov 4, 2013, i spent 99 on this book."



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值