Hello world国际化动态版本

1 资源文件准备

myMess.properties的内容

msg=你好,{0}!今天是{1}。

myMess_en_US.properties的内容

msg=Hello,{0}!Today is {1}.

myMess_zh_CN.properties的内容

msg=\u4f60\u597d\uff0c{0}\uff01\u4eca\u5929\u662f{1}\u3002

2 代码示例

import java.util.*;
import java.text.*;

public class HelloArg
{
	public static void main(String[] args)
	{
		// 定义一个Locale变量
		Locale currentLocale = null;
		// 如果运行程序的指定了两个参数
		if (args.length == 2)
		{
			// 使用运行程序的两个参数构造Locale实例
			currentLocale = new Locale(args[0] , args[1]);
		}
		else
		{
			// 否则直接使用系统默认的Locale
			currentLocale = Locale.getDefault(Locale.Category.FORMAT);
		}
		// 根据Locale加载语言资源
		ResourceBundle bundle = ResourceBundle
			.getBundle("myMess" , currentLocale);
		// 取得已加载的语言资源文件中msg对应消息
		String msg = bundle.getString("msg");
		// 使用MessageFormat为带占位符的字符串传入参数
		if(args.length == 2)
		{
			System.out.println(MessageFormat.format(msg
					, args[0] , args[1]));
		}
		else
		{
			System.out.println(MessageFormat.format(msg
					, "cakin24" , new Date()));	
		}
	}
}

扫描二维码关注公众号,回复: 585518 查看本文章

3 运行结果

第一种情况:不输入参数的结果

你好,cakin24!今天是16-9-3 上午9:13。

第二种情况:输入参数的结果

E:\test\Java\First2\test\bin>java HelloArg cqm 2016-9-3
你好,cqm!今天是2016-9-3。

猜你喜欢

转载自cakin24.iteye.com/blog/2322418