Eclipse 提供了方便的国际化实现方式。
例子:
新建项目 i18n
package test;
public class I18NTest { public I18NTest() { String testString = "Hello ,I18N!"; System.out.println(testString); }
public static void main(String[] args) { new I18NTest() ; } } |
在导航器里面右击该类,Source--->Externalize Strings...
<!--EndFragment-->
一直“下一步”,最后,会生成出这两个文件,而I18NTest这个类也改变了:
package test;
public class I18NTest {
public I18NTest() { String testString = Messages.getString("I18NString.hello"); //$NON-NLS-1$ System.out.println(testString); }
public static void main(String[] args) { new I18NTest() ; }
} |
//$NON-NLS-1$ 这个注释是eclipse自己用的,最后的数字 1 表示该行的第几个数字是不用国际化的。
这个类的国际化就这样完成了。
想要这个类随着不同的语言环境得到不同的输出结果,可以在messages.properties的相同目录下建立message_区域代码.properties
在eclipse的运行设置里面添加-nl zh_cn 类似这样的信息,就可以调试不同地区的显示结果。
如果资源文件有多个参数,如:
I18NTest.TestString=My name is {0} ,today is {1} ,date is {2} . |
程序可以改为:
package test;
import java.text.MessageFormat; import java.util.Date;
public class I18NTest {
static String testString = Messages.getString("I18NTest.TestString"); //$NON-NLS-1$
public static void main(String[] args) { String name = "Irving"; //$NON-NLS-1$ String today = "Monday"; //$NON-NLS-1$ Date date = new Date();
String result = MessageFormat.format(testString, new Object[] { name, today, date }); System.out.println(result); } } |
如果想格式化时间,只需要修改资源文件为:
I18NTest.TestString=My name is {0} ,today is {1} ,date is {2,date,yyyy-MM-dd} . |
注意,2之后不能有空格。