How to load a resource bundle from a file resource in Java?

前端 未结 14 846
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 08:19

I have a file called mybundle.txt in c:/temp -

c:/temp/mybundle.txt

How do I load this file into a java.util.Res

14条回答
  •  無奈伤痛
    2020-11-28 09:08

    For JSF Application

    To get resource bundle prop files from a given file path to use them in a JSF app.

    • Set the bundle with URLClassLoader for a class that extends ResourceBundle to load the bundle from the file path.
    • Specify the class at basename property of loadBundle tag.

    For basic implementation of extended RB please see the sample at Sample Customized Resource Bundle

    /* Create this class to make it base class for Loading Bundle for JSF apps */
    public class Message extends ResourceBundle {
            public Messages (){
                    File file = new File("D:\\properties\\i18n");  
                    ClassLoader loader=null;
                       try {
                           URL[] urls = {file.toURI().toURL()};  
                           loader = new URLClassLoader(urls); 
                           ResourceBundle bundle = getBundle("message", FacesContext.getCurrentInstance().getViewRoot().getLocale(), loader);
                           setParent(bundle);
                           } catch (MalformedURLException ex) { }
           }
          .
          .
          .
        }
    

    Otherwise, get the bundle from getBundle method but locale from others source like Locale.getDefault(), the new (RB)class may not require in this case.

提交回复
热议问题