Java 基础小知识一: 使用ResourceBundle 和 MessageFormat 实现国际化信息输出

对于java基础很好的人来说,这些都是很简单的,但是有时候会忘记,准备写些小东西给自己提个醒,大家也分享下:


我在一个java项目中定义了三个properties 文件:

test.properties:

str=Account {0} create successful.


test_en_US.properties:

str=Account {0} create successful.

test_zh_CN.properties:

str=\u8D26\u53F7 {0} \u7533\u8BF7\u6210\u529F

然后写了个java 类:


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


public class ResourceBundleTest {
 
    protected static final String BUNDLE_NAME = "test";
    protected static final String BUNDLE_EXTENSION = "properties";

 /**
  * @param args
  */
 public static void main(String[] args) {
  
		ResourceBundle resb = ResourceBundle.getBundle(BUNDLE_NAME, Locale.getDefault()); 
		String value = MessageFormat.format(resb.getString("str"), "600001");
		System.out.println(value);
 
        Locale localeChina = new Locale("zh", "CN"); 
        ResourceBundle resbChina = ResourceBundle.getBundle(BUNDLE_NAME, localeChina);
        String valueChina = MessageFormat.format(resbChina.getString("str"), "600001");
        System.out.println(valueChina);
        
        Locale localeUS = new Locale("en", "US"); 
        ResourceBundle resbUS = ResourceBundle.getBundle(BUNDLE_NAME, localeUS);
        String valueUS = MessageFormat.format(resbUS.getString("str"), "600001");
        System.out.println(valueUS);
	}

}

输出结果:

Account 600001 create successful.
账号 600001 申请成功
Account 600001 create successful.

设置一下Locale,就可以成功输出了,MessageFormat类起到传输参数的作用,还支持传多个参数,例如给 "{0}{1}{2}" 传参数:

MessageFormat.format("str", "600001","12132","44343");

就行了,很方便。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值