国际化中用类文件替代资源文件

1 使用说明

使用类文件代替资源文件条件

  • 类名必须是baseName_language_country
  • 类必须继承ListResourceBundle

2 代码示例

import java.util.*;

public class myMess_zh_CN extends ListResourceBundle
{
	// 定义资源
	private final Object myData[][]=
	{
		{"msg","{0},你好!今天的日期是{1}"}
	};
	// 重写方法getContents()
	public Object[][] getContents()
	{
		// 该方法返回资源的key-value对
		return myData;
	}
}
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
					, "cakin" , new Date()));	
		}
	}
}

3 运行结果

cakin,你好!今天的日期是16-9-3 上午10:56

4 ResiurceBunld搜索资源文件顺序

(1)baseName_zh_CN.class

(2)baseName_zh_CN.properties

(3)baseName_zh.class

(4)baseName_zh.properties

(5)baseName.class

(6)baseName.properties

猜你喜欢

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