• 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"));
        }

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

  • 相关阅读:
    winform访问https webservice
    rabbitMQ访问失败
    Redis断线测试
    微信消息推送
    线程控制
    Oracle.ManagedDataAccess.dll折腾了我两天
    IPC网络摄像机rtsp视频流web上H5播放方法
    微软补丁下载网站(备忘)
    ABP vnext 种子文件更新
    ABP vnext 使用Swagger账号登录时Chrome浏览器提示【The cookie 'XSRF-TOKEN' has set 'SameSite=None' and must also set 'Secure'.】错误,不能跳转登录
  • 原文地址:https://www.cnblogs.com/anthonyBlog/p/3998669.html
Copyright © 2020-2023  润新知