对于java基础很好的人来说,这些都是很简单的,但是有时候会忘记,准备写些小东西给自己提个醒,大家也分享下:
我在一个java项目中定义了三个properties 文件:
test.properties:
str=Account {0} create successful.
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");
就行了,很方便。