ResourceBundle enRb = ResourceBundle.getBundle("Message",enLocale);
ResourceBundle frRb = ResourceBundle.getBundle("Message",frLocale);
System.out.println(zhRb.getString("info"));
System.out.println(enRb.getString("info"));
System.out.println(frRb.getString("info"));
}
}
PS:以上中文属性如果是中文的话应该将其进行Unicode编码,这样可以避免一些系统所带来的乱码问题
处理动态文本
之前的资源文件中的所有内容实际上都是固定的,而如果现在有些内容,你好,XXX。那么此时就必须在资源文件中进行一些动态文本的配置,设置占位符,这些符号中的内容暂时不固定,而是在程序执行的时候由程序进行设置的,而要想实现这样的功能,则必须使用MessageFormat类。此类在java.text包中定义的。
占位符使用(数字)的形式表示,如果现在表示第一个内容“{0}”、第二个内容“{1}”依次类推。
在MessageFormat类中主要使用format()方法,此方法定义如下:
public static String format(String pattern,Object...arguments)
[java] info=\u4f60\u597d{0}
info=Hello,{0}
info=Bonjour,{0}
info=\u4f60\u597d{0}
info=Hello,{0}
info=Bonjour,{0}
[java] package com.itmyhome;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
public class T {
public static void main(String[] args) throws Exception{
Locale zhLocale = new Locale("zh","CN"); //表示中国地区
Locale enLocale = new Locale("en","US"); //表示美国地区
Locale frLocale = new Locale("fr","FR"); //表示法国地区
ResourceBundle zhRb = ResourceBundle.getBundle("Message",zhLocale);
ResourceBundle enRb = ResourceBundle.getBundle("Message",enLocale);
ResourceBundle frRb = ResourceBundle.getBundle("Message",frLocale);
System.out.println(MessageFormat.format(zhRb.getString("info"), "itmyhome"));
System.out.println(MessageFormat.format(enRb.getString("info"), "itmyhome"));
System.out.println(MessageFormat.format(frRb.getString("info"), "itmyhome"));
}
}
package com.itmyhome;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
public class T {
public static void main(String[] args) throws Exception{
Locale zhLocale = new Locale("zh","CN"); //表示中国地区
Locale enLocale = new Locale("en","US"); //表示美国地区
Locale frLocale = new Locale("fr","FR"); //表示法国地区
ResourceBundle zhRb = ResourceBundle.getBundle("Message",zhLocale);
ResourceBundle enRb = ResourceBundle.getBundle("Message",enLocale);
ResourceBundle frRb = ResourceBundle.getBundle("Message",frLocale);
System.out.println(MessageFormat.format(zhRb.getString("info"), "itmyhome"));
System.out.println(MessageFormat.format(enRb.getString("info"), "itmyhome"));
System.out.println(MessageFormat.format(frRb.getString("info"), "itmyhome"));
}
}
java新特性,可变参数
在JDK1.5之后java增加了新特性的操作,可以向方法中传递可变的参数,以前的定义的方法,实际上里面的参数都是固定个数的
[java] package com.itmyhome;
public class T {
public static void main(String[] args) throws Exception{
fun("java","c++",".net");
fun("itmyhome");
}
public static void fun(Object...args){
for (int i = 0; i < args.length; i++) {
System.err.println(args[i]+"、");
}
}
}
package com.itmyhome;
public class T {
public static void main(String[] args) throws Exception{
fun("java","c++",".net");
fun("itmyhome");
}
public static void fun(Object...args){
for (int i = 0; i < args.length; i++) {
System.err.println(args[i]+"、");
}
}
}
使用一个类代替资源文件
也可以直接使用一个类来存放所有的资源文件内容,但是,此类