【java】读取资源文件key->value,java.util.ResourceBundle

时间:2024-09-20 13:33:50
 package 国际化;

 import java.util.ResourceBundle;

 public class TestResource {
public static void main(String[] args) {
ResourceBundle rb=ResourceBundle.getBundle("TestResource");
System.out.println(rb.getString("name"));
}
}

前提:需要在project的src目录下建立TestResource.properties文件,并输入内容key-value


 package 国际化;

 import java.text.MessageFormat;
import java.util.ResourceBundle; public class TestResource {
public static void main(String[] args) {
ResourceBundle rb=ResourceBundle.getBundle("TestResource");
String str=rb.getString("info");//含有占位符{0}、{1}
System.out.println(MessageFormat.format(str, "中国","北京"));
//运行结果:country:中国,城市:北京
}
}

占位符的使用

【java】读取资源文件key->value,java.util.ResourceBundle


System.out.println(Locale.getDefault());//zh_CN 取得当前语言环境


 package 国际化;

 import java.util.Locale;
import java.util.ResourceBundle; public class TestResource {
public static void main(String[] args) {
Locale locale=new Locale("zh","CN");
ResourceBundle rb=ResourceBundle.getBundle("TestResource", locale);
String str=rb.getString("info");
System.out.println(str); Locale locale2=new Locale("en","US");
ResourceBundle rb2=ResourceBundle.getBundle("TestResource", locale2);
String str2=rb2.getString("info");
System.out.println(str2); ResourceBundle rb3=ResourceBundle.getBundle("TestResource");
//若未指定Locale则默认取当前语言的Locale,此处默认为zh_CN
//若无TestResource_zh_CN_properties文件,则取TestResource.properties
String str3=rb3.getString("info");
System.out.println(str3);
}
}

Locale的使用

【java】读取资源文件key->value,java.util.ResourceBundle