Java: MissingResourceException, "Can't find bundle for base name myMessage, locale zh_CN"

在java中,在多语言国际化时可以用 *.java 类来作为资源文件使用。

1. 首先定义类, 类必须继承ListResourceBundle 

类所在路径为: src/I18N

 1 public class myMessage_en_US extends ListResourceBundle {
 2 
 3     private final Object mydata[][] = { { "hello", "hello!" },
 4             { "greetting", "Love you . {0}" } };
 5 
 6     @Override
 7     protected Object[][] getContents() {
 8         return mydata;
 9     }
10 
11 }

 

2. 编写测试用例,使用资源文件

该文件在default package 包里面

    public static void main() {
        Locale current = new Locale("zh","CN");
        ResourceBundle bundle = ResourceBundle.getBundle("myMessage", current);
        String format = bundle.getString("greetting");
        System.out.println(MessageFormat.format(format, "Jay"));
    }

可惜的是出错了

Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name myMessage, locale zh_CN
    at java.util.ResourceBundle.throwMissingResourceException(Unknown Source)
    at java.util.ResourceBundle.getBundleImpl(Unknown Source)
    at java.util.ResourceBundle.getBundle(Unknown Source)
    at program.I18NTest(program.java:89)
    at program.main(program.java:20)

尝试很多次之后还是不好使,最终把类 myMessage_en_US和调用的main函数都放在了default package下面。好使了

输出结果 

你好,Jay

看来是资源路径的问题,经过各种尝试之后把路径进行了修改,如下

private static void I18NTest() {
        Locale current = new Locale("zh","CN");
        ResourceBundle bundle = ResourceBundle.getBundle("I18N.myMessage", current);
        String format = bundle.getString("greetting");
        System.out.println(MessageFormat.format(format, "Jay"));
    }

 

而不是修改文件存放的路径。

 

posted @ 2014-09-28 17:24  仰望星辰  阅读(2706)  评论(0编辑  收藏  举报