- import java.util.ResourceBundle;
- public class ResourceBundleDemo {
- public static void main(String[] args) {
- ResourceBundle resource = ResourceBundle.getBundle("messages");
- //自动找到对应的.property文件
- System.out.print(resource.getString("onlyfun.caterpillar.welcome")+",");
- System.out.print(resource.getString("onlyfun.caterpillar.name")+"!");
- }
- }
********************************************************************
classpath下的messages.properties文件内容为:
onlyfun.caterpillar.welcome=Hello
onlyfun.caterpillar.name=sky_snow
onlyfun.caterpillar.greeting=Hello{0}This is your first {1}
********************************************************************
- import java.text.MessageFormat;
- import java.util.ResourceBundle;
- public class MessageFormatDemo {
- public static void main(String[] args) {
- try{
- ResourceBundle resource = ResourceBundle.getBundle("messages");
- String message = resource.getString("onlyfun.caterpillar.greeting");
- Object [] params = new Object[]{"skysnow","Java"};
- MessageFormat formatter = new MessageFormat(message);
- System.out.println(formatter.format(params));
- }catch(ArrayIndexOutOfBoundsException e){
- System.out.println("没有指定参数");
- }
- }
- }
______________________________________________________________________________
ResourceBundle实现了更改properties文件时不需要重新编译java文件就可以改变文字输出。